duke-git / lancet Goto Github PK
View Code? Open in Web Editor NEWA comprehensive, efficient, and reusable util function library of Go.
Home Page: https://www.golancet.cn/en/
License: MIT License
A comprehensive, efficient, and reusable util function library of Go.
Home Page: https://www.golancet.cn/en/
License: MIT License
bytesData, err := convertor.ToBytes("0")
if err != nil {
fmt.Println(err)
}
fmt.Println(bytesData) // [4 12 0 1 48]
fmt.Println(convertor.ToString(bytesData)) // ��� 无法转回 "0"
我发现http包内的setFormData函数仅能支持application/x-www-form-urlencoded格式,并不支持multipart/form-data格式。无法通过SendRequest函数来实现上传文件的功能。
本来是打算提一个pr看看能否直接添加支持,不过在实现后发现ut测试需要一个支持上传文件的url地址来做支撑。如果可以的话也可以给出一个相应的接口,我可以实现这个功能。
或者,考虑再多新增一个mock的工具类?
关于AesCbcEncrypt()和AesCbcDecrypt()中iv使用 key[:blockSize]是基于什么决定的,这样是不是和其他语言的对接不够准确呢?
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/slice"
"github.com/samber/lo"
)
func main() {
arr := []string{"a", "b", "c"}
fmt.Println(slice.Chunk(arr, 10))
fmt.Println(lo.Chunk(arr, 10))
}
输出
[[a] [b] [c]]
[[a b c]]
当chunk长度大于slice长度时,lo库的处理逻辑是正确的
感觉直接在predicate写去重逻辑会比较优雅点
Computing MD5 supports []type input parameters to reduce the cost of string copying.
err := setHeaderAndQueryAndBody(req, reqUrl, params[0], params[1], params[2])
if err != nil {
return nil, err
}
------------
func setHeaderAndQueryAndBody(req *http.Request, reqUrl string, header, queryParam, body interface{}) error {
err := setHeader(req, header)
if err != nil {
return err
}
err = setQueryParam(req, reqUrl, queryParam)
if err != nil {
return err
}
if strings.Contains(req.Header.Get("Content-Type"), "multipart/form-data") || req.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
if formData, ok := queryParam.(url.Values); ok {
err = setBodyByte(req, []byte(formData.Encode()))
}
if formData, ok := queryParam.(map[string]string); ok {
postData := url.Values{}
for k, v := range formData {
postData.Set(k, v)
}
err = setBodyByte(req, []byte(postData.Encode()))
}
} else {
err = setBodyByte(req, body)
}
if err != nil {
return err
}
return nil
}
当只在body中设置application/x-www-form-urlencoded
参数时,参数会被同时设置到Query
,如果将参数转为[]byte, 参数会被丢弃。if-else
判断错误
resp, err := netutil.HttpPost(url, header, queryParams)
if err != nil {
log.Fatal(err)
}
body, _ := ioutil.ReadAll(resp.Body)
var info MyInfo
err = json.Unmarshal(body, &info)
if err != nil {
log.Fatal(err.Error())
return
}
如何使用datetime包获得指定时区的时间呢
https://github.com/duke-git/lancet/blob/main/README_zh-CN.md
validator.md#IsWeakPassword)
例如
func PadEnd(source string, size int, padStr string) string {
len1 := len(source)
len2 := len(padStr)
if len1 >= size || padStr == "" {
return source
}
if len1+len2 >= size {
return source + padStr[:size-len1]
}
fill := strings.Repeat(padStr, (size-len1)/len2+1)[:size-len1]
return source + fill[:size-len1]
}
版本 v1.2.9
复现代码如下:
`
import (
"fmt"
"github.com/duke-git/lancet/convertor"
"github.com/gogf/gf/util/gconv"
"github.com/spf13/cast"
"testing"
)
type Demo struct {
Amount float32 json:"Amount"
}
func precision(params map[string]interface{}) {
fmt.Println(params["Amount"])
fmt.Println(convertor.ToString(params["Amount"]))
fmt.Println(cast.ToString(params["Amount"])) // github.com/spf13/cast
}
func TestSign(t *testing.T) {
in := Demo{Amount: 190.99}
precision(gconv.Map(&in)) // github.com/gogf/gf/util/gconv
}
`
输出:
190.99 190.99000549316406 190.99
只有当使用gconv转换map的时候才会复现(目前来看,没有完全测试),不确定是否是gconv库的问题,但是直接打印map内的值是正确的,且使用cast库结果也是正确的
类似goframe提供的类似设计
https://goframe.org/pages/viewpage.action?pageId=30736711
不然只有get和put 这好像不太方便后续操作
然后能加个并发控制的就最好了
这个工具如果使用go使用低版本进行开发了大量代码,后续升级了高版本的go,会影响原有使用低版本lancet的使用吗。或者也可以同时把lancet升级了吗。
已存在的 zip 文件添加文件或文件夹
cryptor.HmacSha256 uses hex encoding by default, base64 encoding should be added
好像没有创建目录(createDir)的方法?
现在的删除遇到不符的会跳出DropWhile, without 方法不能按条件删除
int[1,2,3,4,5,6]
slice.remove(ints, (v int, index int)=> v%2) return [1,3,5]
slice.remove(ints, (v int, index int)=> index < 3) return [4,5,6]
在使用过程中遇到 windows 环境下需要执行系统命令发现没有相关代码
I'd really like to have a function that takes a slice and a predicate function and returns a map of slices, where the keys are determined by the given predicate function. Essentially the same as GroupBy()
@ samber/lo
.
Functions that make HTTP requests should accept context for cancellation.
Even worse, an http client with default options is used. Not only it doesn't have any timeouts, creating a new HTTP client for every single request isn't efficient and would not utilise HTTP "keep alive" mechanics.
windows下执行system.ExecCommand()会先弹出一个窗口在执行命令,然后这个窗口关闭,
有没有选项让用户选择: 要弹窗,后台直接执行不显示弹窗
我的命令 explorer.exe /e,/select,F:\
常用的字符串截取, fromIndex~toIndex,左闭右开,省去计算长度
字符串查找子串,比如 abcdeabc, 找 abc, 返回0, 从index=1开始找 返回5 , indexFrom
字符串是否包含某个子串, contains 返回bool
数组,find建议在提供一个原始数据查找,目前的 find如果数组存的就是指针, 返回指针的指针,使用时还要在解除引用
有的包名称太长,可以缩短点
dir
├── remove
│ └── test.txt
├── test.txt
└── test_copy.txt
err := fileutil.Zip("./dir/remove", "./remove.zip")
if err != nil {
fmt.Println(err)
}
remove
├── dir
│ └── remove
└── remove
└── test.txt
对 ./dir/remove
子目录进行zip压缩,解压后不应该出现父目录的目录信息
When i run the test unit function TestZipAndUnZip on Windows, I found the os.Remove not remove the temp file successfully beacause it occurred an error "The process cannot access the file because it is being used by another process".
存在不同地方对周末的定义不一样,这里直接用或判断,不太合适,用户自己根据自己业务情况直接用 等于某个 Weekday 就好
辛苦了!
"yyyy-mm-dd hh": "2006-01-02 15:04" ---> "yyyy-mm-dd hh": "2006-01-02 15",
在采用go版本的AesEcbEncrypt 进行加密和AesEcbDecrypt 解密没有问题 (key长度16位)
但是用24 和32位的加密方法加密的结果 在第三方平台无法解密,参考网站结果:http://tool.chacuo.net/cryptaes
最近用到这个库,发现文档查找挺麻烦的,所以把文档搬过去做了一个在线可搜索的文档库
lancet-docs
希望能帮到用到这个库的小伙伴
algolia 搜索引擎还在对接中,等对接完成,搜索更友好快捷准确!
http://ip-api.com/json/ 被伟大的祖国墙了
请检查一下 algorithm.InsertionSort(peoples, comparator) 这个插入排序算法有问题,获取到排序后的元素都是重复的
var peoples = []people{
{Name: "a", Age: 20},
{Name: "b", Age: 10},
{Name: "c", Age: 17},
{Name: "d", Age: 8},
{Name: "e", Age: 28},
}
comparator := &peopleAgeComparator{}
sortedPeople := algorithm.InsertionSort(peoples, comparator)
fmt.Println(sortedPeople)
// out: [{a 20} {a 20} {a 20} {a 20} {a 20}]
去看了下不同地方的iv算法,发现各有不同,目前采取写法是:
iv := encrypted[:aes.BlockSize]
希望这个能开放自定义
select {
case <-time.After(config.retryDuration):
case <-config.context.Done():
return errors.New("retry is cancelled")
}
=》
select {
case <-time.After(config.retryDuration):
return errors.New("timeout!!")
case <-config.context.Done():
return errors.New("retry is cancelled")
}
如果retryDuration超时应该返回,不然会继续执行下面
rand.New(rand.NewSource(time.Now().UnixNano()))
使用纳秒作为种子,并发/运算很快的情况下,同一纳秒下,会生成一样的结果
直接替换成rand.xxx(),没有此问题
iv变量可以改成和key一样吗?现在实现的aes加密 js解密失败
目前打算RSA简单加解密部分都用lancet实现,但是创建密钥时GenerateRsaKey 需要导出文件,能否直接允许返回byte[]
如果存在omitempty,url.vlaues键名中也包含了
全部转成*, 部分转成*,自定义转换策略
// v2.1.12中
func Percent(val, total float64, n int) float64 {
if total == 0 {
return float64(0)
}
tmp := val / total * 100
result := RoundToFloat(tmp, n)
return result
}
// v2.1.13中
func Percent(val, total float64, n int) float64 {
if total == 0 {
return float64(0)
}
tmp := val / total
result := RoundToFloat(tmp, n)
return result
}
// v2.1.12的计算结果
result1 := percent(-30305, 408420, 2)
fmt.Println(result1) // 输出-7.42
// v2.1.13的计算结果
result2 := mathutil.Percent(-30305, 408420, 2)
fmt.Println(result2) //输出-0.07
result3 :=result2 * 100
fmt.Println(result3) //输出-7.000000000000001
不清楚v2.1.13中为何要做这样的调整,需要自行手动乘100,但是这么调整后,出现两个问题
1、保留两位小数后,导致输出是0.07,其实想要的结果是-7.42。丢失了两位精度
2、测试变量float*100会出现精度问题,最终变成-7.000000000000001
希望能够调整会原来的方式
multipart/form-data 中有 boundary,该怎么写?
There is an ambiguity in fileutil.CreateDir
, the incoming path must end with /
.
I input /a/b/c
but create /a/b
.
Since the function's name is CreateDir
, the input params is dir not a file.
It is recommended that the semantics of the function be consistent with the mkdir -p
command of the operating system, that will not cause ambiguity.
mkdir -p /a/b/c
will create /a/b/c
not /a/b
Hello 👋
I found a potential security issue in lancet, how can I get in touch with you in a private way and submit my security report?
Could you add a SECURITY.md file with an e-mail address for me to send further details to? GitHub recommends a security policy to ensure issues are responsibly disclosed, and it would help direct researchers in the future.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.