From 24eb2bbacdc3106a026c651f60353efbad1a0ec3 Mon Sep 17 00:00:00 2001
From: dudaodong Convert color hex to color rgb. Convert color rgb to color hex. Convert string to a boolean value. Use strconv.ParseBool Convert interface to byte slice. Convert string to char slice. Convert a collection of elements to a read-only channels. Convert interface to a float64 value. If param is a invalid floatable, will return 0 and error. Convert interface to a int64 value. If param is a invalid intable, will return 0 and error. Convert interface to json string. If param can't be converted, will return "" and error. Convert interface to string. Convert struct to map, only convert exported field, struct field tag `json` should be set. Encode data to byte slice. Decode byte data to target object. target should be a pointer instance. 颜色值十六进制转rgb 颜色值rgb转十六进制 字符串转布尔类型,使用strconv.ParseBool interface转字节切片. 字符串转字符切片 将切片转为只读channel 将interface转成float64类型,如果参数无法转换,会返回0和error 将interface转成intt64类型,如果参数无法转换,会返回0和error 将interface转成json字符串,如果参数无法转换,会返回""和error 将interface转成字符串 将struct转成map,只会转换struct中可导出的字段。struct中导出字段需要设置json tag标记 将data编码成字节切片 解码字节切片到目标对象,目标对象需要传入一个指针实例子 创建一个传入值的深拷贝, 无法克隆结构体的非导出字段。 Encrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32. Decrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32. Encrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32. Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32. Encrypt or decrypt data with key use AES CTR algorithm. Length of `key` param should be 16, 24 or 32. Encrypt data with key use AES CFB algorithm. Length of `key` param should be 16, 24 or 32. Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32. Enecrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32. Decrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32. Encode string with base64 encoding. Decode a base64 encoded string. Encrypt data with key use DES ECB algorithm. Length of `key` param should be 8. Decrypt data with key use DES ECB algorithm. Length of `key` param should be 8. Encrypt data with key use DES CBC algorithm. Length of `key` param should be 8. Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8. Encrypt or decrypt data with key use DES CTR algorithm. Length of `key` param should be 8. Encrypt data with key use DES CFB algorithm. Length of `key` param should be 8. Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8. Enecrypt data with key use DES OFB algorithm. Length of `key` param should be 8. Decrypt data with key use DES OFB algorithm. Length of `key` param should be 8. Get the md5 hmac hash of string. Get the sha1 hmac hash of string. Get the sha256 hmac hash of string Get the sha512 hmac hash of string. Get the md5 value of string. Get the md5 value of file. Get the sha1 value of string. Get the sha256 value of string. Get the sha512 value of string. Create the rsa public and private key file in current directory. Encrypt data with public key file useing ras algorithm. Decrypt data with private key file useing ras algorithm. 使用AES ECB算法模式加密数据. 参数`key`的长度是16, 24 or 32。 使用AES ECB算法模式解密数据. 参数`key`的长度是16, 24 or 32。
@@ -101,6 +100,7 @@ func main() {
```go
func AesEcbDecrypt(encrypted, key []byte) []byte
```
+
列子:
```go
@@ -113,15 +113,13 @@ import (
func main() {
data := "hello world"
- key := "abcdefghijklmnop"
+ key := "abcdefghijklmnop"
encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key))
- decrypted := cryptor.AesEcbDecrypt(encrypted, []byte(key))
+ decrypted := cryptor.AesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
-
-
### AesCbcEncrypt
使用AES CBC算法模式加密数据. 参数`key`的长度是16, 24 or 32。 使用AES CBC算法模式解密数据. 参数`key`的长度是16, 24 or 32。 使用AES CTR算法模式加密/解密数据. 参数`key`的长度是16, 24 or 32。 使用AES CFB算法模式加密数据. 参数`key`的长度是16, 24 or 32。 使用AES CFB算法模式解密数据. 参数`key`的长度是16, 24 or 32。 使用AES OFB算法模式加密数据. 参数`key`的长度是16, 24 or 32 使用AES OFB算法模式解密数据. 参数`key`的长度是16, 24 or 32 将字符串base64编码 解码base64字符串 使用DES ECB算法模式加密数据. 参数`key`的长度是8 使用DES ECB算法模式解密数据. 参数`key`的长度是8 使用DES CBC算法模式加密数据. 参数`key`的长度是8 使用DES CBC算法模式解密数据. 参数`key`的长度是8 使用DES CTR算法模式加密/解密数据. 参数`key`的长度是8 使用DES CFB算法模式加密数据. 参数`key`的长度是8 使用DES CFB算法模式解密数据. 参数`key`的长度是8 使用DES OFB算法模式加密数据. 参数`key`的长度是8 使用DES OFB算法模式解密数据. 参数`key`的长度是8 获取字符串md5 hmac值 获取字符串sha1 hmac值 获取字符串sha256 hmac值 获取字符串sha512 hmac值 获取字符串md5值 获取文件md5值. 获取字符串sha1值 获取字符串sha256值 获取字符串sha512值 在当前目录下创建rsa私钥文件和公钥文件 用公钥文件ras加密数据 用私钥文件rsa解密数据 Add or sub days to time. Add or sub hours to time. Add or sub minutes to time. Return beginning minute time of day. Return zero time of day. Return begin time of day. Return beginning time of week, week begin from Sunday. Return beginning time of month Return beginning time of year. Return end time minute of day. Return end time hour of day. Return end time hour of day. Return end time of week, week end with Saturday. Return end time of month Return beginning time of year. Get current date string, format is yyyy-mm-dd. Get current time string, format is hh:mm:ss. Get current date time string, format is yyyy-mm-dd hh:mm:ss. Return timestamp of zero hour (timestamp of 00:00). Return timestamp of zero hour (timestamp of 23:59). Format time to string, `format` param specification see note 1. Format string to time, `format` param specification see note 1. Return unix timestamp of current time Return unix timestamp of specified int64 value. Return unix timestamp of specified time string, t should be "yyyy-mm-dd hh:mm:ss". Return unix timestamp of specified iso8601 time string. Return unix timestamp. Return time string 'yyyy-mm-dd hh:mm:ss'. Return the time string which format is specified tpl. Return iso8601 time string. 将日期加/减天数 将日期加/减小时数 将日期加/减分钟数 返回指定时间的分钟开始时间 返回指定时间的小时开始时间 返回指定时间的当天开始时间 返回指定时间的星期开始时间 返回指定时间的当月开始时间 返回指定时间的当年开始时间 返回指定时间的分钟结束时间 返回指定时间的小时结束时间 返回指定时间的当天结束时间. 返回指定时间的星期结束时间 返回指定时间的月份结束时间 返回指定时间的年份结束时间 获取当天日期,返回格式:yyyy-mm-dd 获取当时时间,返回格式:hh:mm:ss 获取当时日期和时间,返回格式:yyyy-mm-dd hh:mm:ss. 获取零时时间戳(timestamp of 00:00). 获取午夜时间戳(timestamp of 23:59). 将日期格式化成字符串,`format` 参数格式参考注1 将字符串格式化成时间,`format` 参数格式参考注1 创建一个当前时间的unix时间戳 创建一个unix时间戳 创建一个yyyy-mm-dd hh:mm:ss格式时间字符串的unix时间戳 创建一个iso8601格式时间字符串的unix时间戳 返回unix时间戳 返回格式'yyyy-mm-dd hh:mm:ss'的日期字符串 返回tpl格式指定的日期字符串 返回iso8601日期字符串 Clear the file content, write empty string to the file. Create directory in absolute path. param `absPath` like /a/, /a/b/. Create file in path. return true if create succeed. Copy src file to dest file. If dest file exist will overwrite it. Return file mode infomation. Get file mime type, 'file' param's type should be string or *os.File. Checks if a file or directory exists. Checks if a file is symbol link or not. Checks if the path is directy or not. List all file names in given path. Remove the file of path. Return string of file content. Read file line by line, and return slice of lines Create a zip file of fpath, fpath could be a file or a directory. Unzip the file and save it to dest path. 清空文件内容 使用绝对路径创建嵌套目录,例如/a/, /a/b/ 创建文件,创建成功返回true, 否则返回false 拷贝文件,会覆盖原有的拷贝文件 获取文件mode信息 获取文件mime类型, 'file'参数的类型必须是string或者*os.File 判断文件或目录是否存在 判断文件是否是符号链接 判断目录是否存在 返回目录下所有文件名 删除文件 读取文件内容并返回字符串 按行读取文件内容,返回字符串切片包含每一行 zip压缩文件, fpath参数可以是文件或目录 zip解压缩文件并保存在目录中 Add comma to number by every 3 numbers from right. ahead by symbol char.
Param should be number or numberic string.
用逗号每隔3位分割数字/字符串,签名添加符号。参数必须是数字或者可以转为数字的字符串
函数签名: @@ -35,6 +37,7 @@ import ( ```go func Comma(v interface{}, symbol string) string ``` + 例子: ```go diff --git a/docs/function.md b/docs/function.md index a0bfc38..8308f29 100644 --- a/docs/function.md +++ b/docs/function.md @@ -1,4 +1,5 @@ # Function + Package function can control the flow of function execution and support part of functional programming. @@ -11,6 +12,7 @@ Package function can control the flow of function execution and support part of ## Usage: + ```go import ( "github.com/duke-git/lancet/function" @@ -20,21 +22,21 @@ import ( ## Index -- [After](#After) -- [Before](#Before) -- [Curry](#Curry) -- [Compose](#Compose) -- [Debounced](#Debounced) -- [Delay](#Delay) -- [Watcher](#Watcher) + +- [After](#After) +- [Before](#Before) +- [Curry](#Curry) +- [Compose](#Compose) +- [Debounced](#Debounced) +- [Delay](#Delay) +- [Watcher](#Watcher) ## Documentation - - ### After +Creates a function that invokes given func once it's called n or more times.
Signature: @@ -42,6 +44,7 @@ import ( ```go func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value ``` + Example: ```go @@ -53,33 +56,31 @@ import ( ) func main() { - arr := []string{"a", "b"} - f := function.After(len(arr), func(i int) int { - fmt.Println("last print") - return i - }) + arr := []string{"a", "b"} + f := function.After(len(arr), func(i int) int { + fmt.Println("last print") + return i + }) - type cb func(args ...interface{}) []reflect.Value - print := func(i int, s string, fn cb) { - fmt.Printf("arr[%d] is %s \n", i, s) - fn(i) - } + type cb func(args ...interface{}) []reflect.Value + print := func(i int, s string, fn cb) { + fmt.Printf("arr[%d] is %s \n", i, s) + fn(i) + } - fmt.Println("arr is", arr) - for i := 0; i < len(arr); i++ { - print(i, arr[i], f) - } + fmt.Println("arr is", arr) + for i := 0; i < len(arr); i++ { + print(i, arr[i], f) + } //output: // arr is [a b] - // arr[0] is a - // arr[1] is b + // arr[0] is a + // arr[1] is b // last print } ``` - - ### Beforecreates a function that invokes func once it's called less than n times.
@@ -89,6 +90,7 @@ func main() { ```go func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value ``` + Example: ```go @@ -103,29 +105,27 @@ import ( func main() { assert := internal.NewAssert(t, "TestBefore") - arr := []string{"a", "b", "c", "d", "e"} - f := function.Before(3, func(i int) int { - return i - }) + arr := []string{"a", "b", "c", "d", "e"} + f := function.Before(3, func(i int) int { + return i + }) - var res []int64 - type cb func(args ...interface{}) []reflect.Value - appendStr := func(i int, s string, fn cb) { - v := fn(i) - res = append(res, v[0].Int()) - } + var res []int64 + type cb func(args ...interface{}) []reflect.Value + appendStr := func(i int, s string, fn cb) { + v := fn(i) + res = append(res, v[0].Int()) + } - for i := 0; i < len(arr); i++ { - appendStr(i, arr[i], f) - } + for i := 0; i < len(arr); i++ { + appendStr(i, arr[i], f) + } - expected := []int64{0, 1, 2, 2, 2} - assert.Equal(expected, res) + expected := []int64{0, 1, 2, 2, 2} + assert.Equal(expected, res) } ``` - - ### CurryMake a curry function.
@@ -136,6 +136,7 @@ func main() { type Fn func(...interface{}) interface{} func (f Fn) Curry(i interface{}) func(...interface{}) interface{} ``` + Example: ```go @@ -148,19 +149,17 @@ import ( func main() { add := func(a, b int) int { - return a + b - } - var addCurry function.Fn = func(values ...interface{}) interface{} { - return add(values[0].(int), values[1].(int)) - } - add1 := addCurry.Curry(1) - result := add1(2) + return a + b + } + var addCurry function.Fn = func(values ...interface{}) interface{} { + return add(values[0].(int), values[1].(int)) + } + add1 := addCurry.Curry(1) + result := add1(2) fmt.Println(result) //3 } ``` - - ### ComposeCompose the function list from right to left, then return the composed function.
@@ -170,6 +169,7 @@ func main() { ```go func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{} ``` + Example: ```go @@ -182,21 +182,19 @@ import ( func main() { add1 := func(v ...interface{}) interface{} { - return v[0].(int) + 1 - } + return v[0].(int) + 1 + } add2 := func(v ...interface{}) interface{} { - return v[0].(int) + 2 - } + return v[0].(int) + 2 + } add3 := function.Compose(add1, add2) - result := add3(1) + result := add3(1) fmt.Println(result) //4 } ``` - - ### DebouncedCreates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.
@@ -206,6 +204,7 @@ func main() { ```go func Debounced(fn func(), duration time.Duration) func() ``` + Example: ```go @@ -218,27 +217,25 @@ import ( func main() { count := 0 - add := func() { - count++ - } + add := func() { + count++ + } - debouncedAdd := function.Debounced(add, 50*time.Microsecond) - function.debouncedAdd() - function.debouncedAdd() - function.debouncedAdd() - function.debouncedAdd() + debouncedAdd := function.Debounced(add, 50*time.Microsecond) + function.debouncedAdd() + function.debouncedAdd() + function.debouncedAdd() + function.debouncedAdd() - time.Sleep(100 * time.Millisecond) - fmt.Println(count) //1 + time.Sleep(100 * time.Millisecond) + fmt.Println(count) //1 - function.debouncedAdd() - time.Sleep(100 * time.Millisecond) - fmt.Println(count) //2 + function.debouncedAdd() + time.Sleep(100 * time.Millisecond) + fmt.Println(count) //2 } ``` - - ### DelayInvoke function after delayed time.
@@ -248,6 +245,7 @@ func main() { ```go func Delay(delay time.Duration, fn interface{}, args ...interface{}) ``` + Example: ```go @@ -259,15 +257,13 @@ import ( ) func main() { - var print = func(s string) { - fmt.Println(count) //test delay - } - function.Delay(2*time.Second, print, "test delay") + var print = func(s string) { + fmt.Println(count) //test delay + } + function.Delay(2*time.Second, print, "test delay") } ``` - - ### ScheduleInvoke function every duration time, until close the returned bool chan.
@@ -277,6 +273,7 @@ func main() { ```go func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool ``` + Example: ```go @@ -289,20 +286,18 @@ import ( func main() { var res []string - appendStr := func(s string) { - res = append(res, s) - } + appendStr := func(s string) { + res = append(res, s) + } - stop := function.Schedule(1*time.Second, appendStr, "*") - time.Sleep(5 * time.Second) - close(stop) + stop := function.Schedule(1*time.Second, appendStr, "*") + time.Sleep(5 * time.Second) + close(stop) - fmt.Println(res) //[* * * * *] + fmt.Println(res) //[* * * * *] } ``` - - ### WatcherWatcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.
@@ -311,15 +306,16 @@ func main() { ```go type Watcher struct { - startTime int64 - stopTime int64 - excuting bool + startTime int64 + stopTime int64 + excuting bool } func (w *Watcher) Start() //start the watcher func (w *Watcher) Stop() //stop the watcher func (w *Watcher) Reset() //reset the watcher func (w *Watcher) GetElapsedTime() time.Duration //get the elapsed time of function execution ``` + Example: ```go @@ -332,33 +328,30 @@ import ( func main() { w := &function.Watcher{} - w.Start() + w.Start() - longRunningTask() + longRunningTask() - fmt.Println(w.excuting) //true + fmt.Println(w.excuting) //true - w.Stop() + w.Stop() - eapsedTime := w.GetElapsedTime().Milliseconds() - fmt.Println(eapsedTime) + eapsedTime := w.GetElapsedTime().Milliseconds() + fmt.Println(eapsedTime) - w.Reset() + w.Reset() - fmt.Println(w.excuting) //false + fmt.Println(w.excuting) //false - fmt.Println(w.startTime) //0 - fmt.Println(w.stopTime) //0 + fmt.Println(w.startTime) //0 + fmt.Println(w.stopTime) //0 } func longRunningTask() { - var slice []int64 - for i := 0; i < 10000000; i++ { - slice = append(slice, int64(i)) - } + var slice []int64 + for i := 0; i < 10000000; i++ { + slice = append(slice, int64(i)) + } } ``` - - - diff --git a/docs/function_zh-CN.md b/docs/function_zh-CN.md index 5717a75..7761567 100644 --- a/docs/function_zh-CN.md +++ b/docs/function_zh-CN.md @@ -1,5 +1,6 @@ # Function -function函数包控制函数执行流程,包含部分函数式编程。 + +function 函数包控制函数执行流程,包含部分函数式编程。 @@ -11,6 +12,7 @@ function函数包控制函数执行流程,包含部分函数式编程。 ## 用法: + ```go import ( "github.com/duke-git/lancet/function" @@ -20,21 +22,21 @@ import ( ## 目录 -- [After](#After) -- [Before](#Before) -- [Curry](#Curry) -- [Compose](#Compose) -- [Debounced](#Debounced) -- [Delay](#Delay) -- [Watcher](#Watcher) + +- [After](#After) +- [Before](#Before) +- [Curry](#Curry) +- [Compose](#Compose) +- [Debounced](#Debounced) +- [Delay](#Delay) +- [Watcher](#Watcher) ## 文档 - - ### After +创建一个函数,当他被调用n或更多次之后将马上触发fn
函数签名: @@ -42,6 +44,7 @@ import ( ```go func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value ``` + 例子: ```go @@ -53,33 +56,31 @@ import ( ) func main() { - arr := []string{"a", "b"} - f := function.After(len(arr), func(i int) int { - fmt.Println("last print") - return i - }) + arr := []string{"a", "b"} + f := function.After(len(arr), func(i int) int { + fmt.Println("last print") + return i + }) - type cb func(args ...interface{}) []reflect.Value - print := func(i int, s string, fn cb) { - fmt.Printf("arr[%d] is %s \n", i, s) - fn(i) - } + type cb func(args ...interface{}) []reflect.Value + print := func(i int, s string, fn cb) { + fmt.Printf("arr[%d] is %s \n", i, s) + fn(i) + } - fmt.Println("arr is", arr) - for i := 0; i < len(arr); i++ { - print(i, arr[i], f) - } + fmt.Println("arr is", arr) + for i := 0; i < len(arr); i++ { + print(i, arr[i], f) + } //output: // arr is [a b] - // arr[0] is a - // arr[1] is b + // arr[0] is a + // arr[1] is b // last print } ``` - - ### Before创建一个函数,调用次数不超过n次,之后再调用这个函数,将返回一次最后调用fn的结果
@@ -89,6 +90,7 @@ func main() { ```go func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value ``` + 例子: ```go @@ -101,31 +103,29 @@ import ( ) func main() { - assert := internal.NewAssert(t, "TestBefore") + assert := internal.NewAssert(t, "TestBefore") - arr := []string{"a", "b", "c", "d", "e"} - f := function.Before(3, func(i int) int { - return i - }) + arr := []string{"a", "b", "c", "d", "e"} + f := function.Before(3, func(i int) int { + return i + }) - var res []int64 - type cb func(args ...interface{}) []reflect.Value - appendStr := func(i int, s string, fn cb) { - v := fn(i) - res = append(res, v[0].Int()) - } + var res []int64 + type cb func(args ...interface{}) []reflect.Value + appendStr := func(i int, s string, fn cb) { + v := fn(i) + res = append(res, v[0].Int()) + } - for i := 0; i < len(arr); i++ { - appendStr(i, arr[i], f) - } + for i := 0; i < len(arr); i++ { + appendStr(i, arr[i], f) + } - expected := []int64{0, 1, 2, 2, 2} - assert.Equal(expected, res) + expected := []int64{0, 1, 2, 2, 2} + assert.Equal(expected, res) } ``` - - ### Curry创建一个柯里化的函数
@@ -136,6 +136,7 @@ func main() { type Fn func(...interface{}) interface{} func (f Fn) Curry(i interface{}) func(...interface{}) interface{} ``` + 例子: ```go @@ -147,20 +148,18 @@ import ( ) func main() { - add := func(a, b int) int { - return a + b - } - var addCurry function.Fn = func(values ...interface{}) interface{} { - return add(values[0].(int), values[1].(int)) - } - add1 := addCurry.Curry(1) - result := add1(2) - fmt.Println(result) //3 + add := func(a, b int) int { + return a + b + } + var addCurry function.Fn = func(values ...interface{}) interface{} { + return add(values[0].(int), values[1].(int)) + } + add1 := addCurry.Curry(1) + result := add1(2) + fmt.Println(result) //3 } ``` - - ### Compose从右至左组合函数列表fnList, 返回组合后的函数
@@ -170,6 +169,7 @@ func main() { ```go func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{} ``` + 例子: ```go @@ -181,22 +181,20 @@ import ( ) func main() { - add1 := func(v ...interface{}) interface{} { - return v[0].(int) + 1 - } - add2 := func(v ...interface{}) interface{} { - return v[0].(int) + 2 - } + add1 := func(v ...interface{}) interface{} { + return v[0].(int) + 1 + } + add2 := func(v ...interface{}) interface{} { + return v[0].(int) + 2 + } - add3 := function.Compose(add1, add2) - result := add3(1) + add3 := function.Compose(add1, add2) + result := add3(1) - fmt.Println(result) //4 + fmt.Println(result) //4 } ``` - - ### Debounced创建一个 debounced 函数,该函数延迟调用 fn 直到自上次调用 debounced 函数后等待持续时间过去。
@@ -206,6 +204,7 @@ func main() { ```go func Debounced(fn func(), duration time.Duration) func() ``` + 例子: ```go @@ -217,28 +216,26 @@ import ( ) func main() { - count := 0 - add := func() { - count++ - } + count := 0 + add := func() { + count++ + } - debouncedAdd := function.Debounced(add, 50*time.Microsecond) - function.debouncedAdd() - function.debouncedAdd() - function.debouncedAdd() - function.debouncedAdd() + debouncedAdd := function.Debounced(add, 50*time.Microsecond) + function.debouncedAdd() + function.debouncedAdd() + function.debouncedAdd() + function.debouncedAdd() - time.Sleep(100 * time.Millisecond) - fmt.Println(count) //1 + time.Sleep(100 * time.Millisecond) + fmt.Println(count) //1 - function.debouncedAdd() - time.Sleep(100 * time.Millisecond) - fmt.Println(count) //2 + function.debouncedAdd() + time.Sleep(100 * time.Millisecond) + fmt.Println(count) //2 } ``` - - ### Delay延迟delay时间后调用函数
@@ -248,6 +245,7 @@ func main() { ```go func Delay(delay time.Duration, fn interface{}, args ...interface{}) ``` + 例子: ```go @@ -259,15 +257,13 @@ import ( ) func main() { - var print = func(s string) { - fmt.Println(count) //test delay - } - function.Delay(2*time.Second, print, "test delay") + var print = func(s string) { + fmt.Println(count) //test delay + } + function.Delay(2*time.Second, print, "test delay") } ``` - - ### Schedule每次持续时间调用函数,直到关闭返回的 bool chan
@@ -277,6 +273,7 @@ func main() { ```go func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool ``` + 例子: ```go @@ -289,20 +286,18 @@ import ( func main() { var res []string - appendStr := func(s string) { - res = append(res, s) - } + appendStr := func(s string) { + res = append(res, s) + } - stop := function.Schedule(1*time.Second, appendStr, "*") - time.Sleep(5 * time.Second) - close(stop) + stop := function.Schedule(1*time.Second, appendStr, "*") + time.Sleep(5 * time.Second) + close(stop) fmt.Println(res) //[* * * * *] } ``` - - ### WatcherWatcher 用于记录代码执行时间。可以启动/停止/重置手表定时器。获取函数执行的时间。
@@ -311,15 +306,16 @@ func main() { ```go type Watcher struct { - startTime int64 - stopTime int64 - excuting bool + startTime int64 + stopTime int64 + excuting bool } func (w *Watcher) Start() //start the watcher func (w *Watcher) Stop() //stop the watcher func (w *Watcher) Reset() //reset the watcher func (w *Watcher) GetElapsedTime() time.Duration //get the elapsed time of function execution ``` + 例子: ```go @@ -332,33 +328,30 @@ import ( func main() { w := &function.Watcher{} - w.Start() + w.Start() - longRunningTask() + longRunningTask() - fmt.Println(w.excuting) //true + fmt.Println(w.excuting) //true - w.Stop() + w.Stop() - eapsedTime := w.GetElapsedTime().Milliseconds() - fmt.Println(eapsedTime) + eapsedTime := w.GetElapsedTime().Milliseconds() + fmt.Println(eapsedTime) - w.Reset() + w.Reset() - fmt.Println(w.excuting) //false + fmt.Println(w.excuting) //false - fmt.Println(w.startTime) //0 - fmt.Println(w.stopTime) //0 + fmt.Println(w.startTime) //0 + fmt.Println(w.stopTime) //0 } func longRunningTask() { - var slice []int64 - for i := 0; i < 10000000; i++ { - slice = append(slice, int64(i)) - } + var slice []int64 + for i := 0; i < 10000000; i++ { + slice = append(slice, int64(i)) + } } ``` - - - diff --git a/docs/mathutil.md b/docs/mathutil.md index 6f719b7..f536259 100644 --- a/docs/mathutil.md +++ b/docs/mathutil.md @@ -1,4 +1,5 @@ # Mathutil + Package mathutil implements some functions for math calculation. @@ -7,10 +8,10 @@ Package mathutil implements some functions for math calculation. [https://github.com/duke-git/lancet/blob/v1/mathutil/mathutil.go](https://github.com/duke-git/lancet/blob/v1/mathutil/mathutil.go) - ## Example: + ```go import ( "github.com/duke-git/lancet/mathutil" @@ -20,20 +21,21 @@ import ( ## Index -- [Exponent](#Exponent) -- [Fibonacci](#Fibonacci) -- [Factorial](#Factorial) -- [Percent](#Percent) -- [RoundToFloat](#RoundToFloat) -- [RoundToString](#RoundToString) -- [TruncRound](#TruncRound) + +- [Exponent](#Exponent) +- [Fibonacci](#Fibonacci) +- [Factorial](#Factorial) +- [Percent](#Percent) +- [RoundToFloat](#RoundToFloat) +- [RoundToString](#RoundToString) +- [TruncRound](#TruncRound) ## Documentation - ### Exponent +Calculate x to the nth power.
Signature: @@ -41,6 +43,7 @@ import ( ```go func Exponent(x, n int64) int64 ``` + Example: ```go @@ -52,15 +55,14 @@ import ( ) func main() { - fmt.Println(mathutil.Exponent(10, 0)) //1 - fmt.Println(mathutil.Exponent(10, 1)) //10 - fmt.Println(mathutil.Exponent(10, 2)) //100 + fmt.Println(mathutil.Exponent(10, 0)) //1 + fmt.Println(mathutil.Exponent(10, 1)) //10 + fmt.Println(mathutil.Exponent(10, 2)) //100 } ``` - - ### Fibonacci +Calculate the nth number of fibonacci sequence.
Signature: @@ -68,6 +70,7 @@ func main() { ```go func Fibonacci(first, second, n int) int ``` + Example: ```go @@ -79,17 +82,16 @@ import ( ) func main() { - fmt.Println(mathutil.Fibonacci(1, 1, 1)) //1 - fmt.Println(mathutil.Fibonacci(1, 1, 2)) //1 - fmt.Println(mathutil.Fibonacci(1, 1, 3)) //2 - fmt.Println(mathutil.Fibonacci(1, 1, 4)) //3 - fmt.Println(mathutil.Fibonacci(1, 1, 5)) //5 + fmt.Println(mathutil.Fibonacci(1, 1, 1)) //1 + fmt.Println(mathutil.Fibonacci(1, 1, 2)) //1 + fmt.Println(mathutil.Fibonacci(1, 1, 3)) //2 + fmt.Println(mathutil.Fibonacci(1, 1, 4)) //3 + fmt.Println(mathutil.Fibonacci(1, 1, 5)) //5 } ``` - - ### Factorial +Calculate the factorial of x.
Signature: @@ -97,6 +99,7 @@ func main() { ```go func Factorial(x uint) uint ``` + Example: ```go @@ -108,16 +111,15 @@ import ( ) func main() { - fmt.Println(mathutil.Factorial(0)) //1 - fmt.Println(mathutil.Factorial(1)) //1 - fmt.Println(mathutil.Factorial(2)) //2 - fmt.Println(mathutil.Factorial(3)) //6 + fmt.Println(mathutil.Factorial(0)) //1 + fmt.Println(mathutil.Factorial(1)) //1 + fmt.Println(mathutil.Factorial(2)) //2 + fmt.Println(mathutil.Factorial(3)) //6 } ``` - - ### Percent +calculate the percentage of val to total, retain n decimal places.
Signature: @@ -125,6 +127,7 @@ func main() { ```go func Percent(val, total float64, n int) float64 ``` + Example: ```go @@ -136,14 +139,13 @@ import ( ) func main() { - fmt.Println(mathutil.Percent(1, 2, 2)) //1 - fmt.Println(mathutil.Percent(0.1, 0.3, 2)) //33.33 + fmt.Println(mathutil.Percent(1, 2, 2)) //1 + fmt.Println(mathutil.Percent(0.1, 0.3, 2)) //33.33 } ``` - - ### RoundToFloat +Round float up to n decimal places.
Signature: @@ -151,6 +153,7 @@ func main() { ```go func RoundToFloat(x float64, n int) float64 ``` + Example: ```go @@ -162,18 +165,16 @@ import ( ) func main() { - fmt.Println(mathutil.RoundToFloat(0, 0)) //0 - fmt.Println(mathutil.RoundToFloat(0, 1)) //0 - fmt.Println(mathutil.RoundToFloat(0.124, 2)) //0.12 - fmt.Println(mathutil.RoundToFloat(0.125, 2)) //0.13 - fmt.Println(mathutil.RoundToFloat(0.125, 3)) //0.125 + fmt.Println(mathutil.RoundToFloat(0, 0)) //0 + fmt.Println(mathutil.RoundToFloat(0, 1)) //0 + fmt.Println(mathutil.RoundToFloat(0.124, 2)) //0.12 + fmt.Println(mathutil.RoundToFloat(0.125, 2)) //0.13 + fmt.Println(mathutil.RoundToFloat(0.125, 3)) //0.125 } ``` - - - ### RoundToString +Round float up to n decimal places. will return string.
Signature: @@ -181,6 +182,7 @@ func main() { ```go func RoundToString(x float64, n int) string ``` + Example: ```go @@ -192,17 +194,16 @@ import ( ) func main() { - fmt.Println(mathutil.RoundToString(0, 0)) //"0" - fmt.Println(mathutil.RoundToString(0, 1)) //"0.0: - fmt.Println(mathutil.RoundToString(0.124, 2)) //"0.12" - fmt.Println(mathutil.RoundToString(0.125, 2)) //"0.13" - fmt.Println(mathutil.RoundToString(0.125, 3)) //"0.125" + fmt.Println(mathutil.RoundToString(0, 0)) //"0" + fmt.Println(mathutil.RoundToString(0, 1)) //"0.0: + fmt.Println(mathutil.RoundToString(0.124, 2)) //"0.12" + fmt.Println(mathutil.RoundToString(0.125, 2)) //"0.13" + fmt.Println(mathutil.RoundToString(0.125, 3)) //"0.125" } ``` - - ### TruncRound +Round float off n decimal places.
Signature: @@ -210,6 +211,7 @@ func main() { ```go func TruncRound(x float64, n int) float64 ``` + Example: ```go @@ -221,13 +223,10 @@ import ( ) func main() { - fmt.Println(mathutil.TruncRound(0, 0)) //0 - fmt.Println(mathutil.TruncRound(0, 1)) //0 - fmt.Println(mathutil.TruncRound(0.124, 2)) //0.12 - fmt.Println(mathutil.TruncRound(0.125, 2)) //0.12 - fmt.Println(mathutil.TruncRound(0.125, 3)) //0.125 + fmt.Println(mathutil.TruncRound(0, 0)) //0 + fmt.Println(mathutil.TruncRound(0, 1)) //0 + fmt.Println(mathutil.TruncRound(0.124, 2)) //0.12 + fmt.Println(mathutil.TruncRound(0.125, 2)) //0.12 + fmt.Println(mathutil.TruncRound(0.125, 3)) //0.125 } ``` - - - diff --git a/docs/mathutil_zh-CN.md b/docs/mathutil_zh-CN.md index 758c23f..bb7cdfb 100644 --- a/docs/mathutil_zh-CN.md +++ b/docs/mathutil_zh-CN.md @@ -1,5 +1,6 @@ # Mathutil -mathutil包实现了一些数学计算的函数. + +mathutil 包实现了一些数学计算的函数. @@ -7,10 +8,10 @@ mathutil包实现了一些数学计算的函数. [https://github.com/duke-git/lancet/blob/v1/mathutil/mathutil.go](https://github.com/duke-git/lancet/blob/v1/mathutil/mathutil.go) - ## 用法: + ```go import ( "github.com/duke-git/lancet/mathutil" @@ -20,21 +21,22 @@ import ( ## 目录 -- [Exponent](#Exponent) -- [Fibonacci](#Fibonacci) -- [Factorial](#Factorial) -- [Percent](#Percent) -- [RoundToFloat](#RoundToFloat) -- [RoundToString](#RoundToString) -- [TruncRound](#TruncRound) +- [Exponent](#Exponent) +- [Fibonacci](#Fibonacci) +- [Factorial](#Factorial) + +- [Percent](#Percent) +- [RoundToFloat](#RoundToFloat) +- [RoundToString](#RoundToString) +- [TruncRound](#TruncRound) ## Documentation - ### Exponent +指数计算(x的n次方)
函数签名: @@ -42,6 +44,7 @@ import ( ```go func Exponent(x, n int64) int64 ``` + 例子: ```go @@ -53,15 +56,14 @@ import ( ) func main() { - fmt.Println(mathutil.Exponent(10, 0)) //1 - fmt.Println(mathutil.Exponent(10, 1)) //10 - fmt.Println(mathutil.Exponent(10, 2)) //100 + fmt.Println(mathutil.Exponent(10, 0)) //1 + fmt.Println(mathutil.Exponent(10, 1)) //10 + fmt.Println(mathutil.Exponent(10, 2)) //100 } ``` - - ### Fibonacci +计算斐波那契数列的第n个数
函数签名: @@ -69,6 +71,7 @@ func main() { ```go func Fibonacci(first, second, n int) int ``` + 例子: ```go @@ -80,17 +83,16 @@ import ( ) func main() { - fmt.Println(mathutil.Fibonacci(1, 1, 1)) //1 - fmt.Println(mathutil.Fibonacci(1, 1, 2)) //1 - fmt.Println(mathutil.Fibonacci(1, 1, 3)) //2 - fmt.Println(mathutil.Fibonacci(1, 1, 4)) //3 - fmt.Println(mathutil.Fibonacci(1, 1, 5)) //5 + fmt.Println(mathutil.Fibonacci(1, 1, 1)) //1 + fmt.Println(mathutil.Fibonacci(1, 1, 2)) //1 + fmt.Println(mathutil.Fibonacci(1, 1, 3)) //2 + fmt.Println(mathutil.Fibonacci(1, 1, 4)) //3 + fmt.Println(mathutil.Fibonacci(1, 1, 5)) //5 } ``` - - ### Factorial +计算阶乘
函数签名: @@ -98,6 +100,7 @@ func main() { ```go func Factorial(x uint) uint ``` + 例子: ```go @@ -109,16 +112,15 @@ import ( ) func main() { - fmt.Println(mathutil.Factorial(0)) //1 - fmt.Println(mathutil.Factorial(1)) //1 - fmt.Println(mathutil.Factorial(2)) //2 - fmt.Println(mathutil.Factorial(3)) //6 + fmt.Println(mathutil.Factorial(0)) //1 + fmt.Println(mathutil.Factorial(1)) //1 + fmt.Println(mathutil.Factorial(2)) //2 + fmt.Println(mathutil.Factorial(3)) //6 } ``` - - ### Percent +计算百分比,保留n位小数
函数签名: @@ -126,6 +128,7 @@ func main() { ```go func Percent(val, total float64, n int) float64 ``` + 例子: ```go @@ -137,14 +140,13 @@ import ( ) func main() { - fmt.Println(mathutil.Percent(1, 2, 2)) //1 - fmt.Println(mathutil.Percent(0.1, 0.3, 2)) //33.33 + fmt.Println(mathutil.Percent(1, 2, 2)) //1 + fmt.Println(mathutil.Percent(0.1, 0.3, 2)) //33.33 } ``` - - ### RoundToFloat +四舍五入,保留n位小数
函数签名: @@ -152,6 +154,7 @@ func main() { ```go func RoundToFloat(x float64, n int) float64 ``` + 例子: ```go @@ -163,18 +166,16 @@ import ( ) func main() { - fmt.Println(mathutil.RoundToFloat(0, 0)) //0 - fmt.Println(mathutil.RoundToFloat(0, 1)) //0 - fmt.Println(mathutil.RoundToFloat(0.124, 2)) //0.12 - fmt.Println(mathutil.RoundToFloat(0.125, 2)) //0.13 - fmt.Println(mathutil.RoundToFloat(0.125, 3)) //0.125 + fmt.Println(mathutil.RoundToFloat(0, 0)) //0 + fmt.Println(mathutil.RoundToFloat(0, 1)) //0 + fmt.Println(mathutil.RoundToFloat(0.124, 2)) //0.12 + fmt.Println(mathutil.RoundToFloat(0.125, 2)) //0.13 + fmt.Println(mathutil.RoundToFloat(0.125, 3)) //0.125 } ``` - - - ### RoundToString +四舍五入,保留n位小数,返回字符串
函数签名: @@ -182,6 +183,7 @@ func main() { ```go func RoundToString(x float64, n int) string ``` + 例子: ```go @@ -193,17 +195,16 @@ import ( ) func main() { - fmt.Println(mathutil.RoundToString(0, 0)) //"0" - fmt.Println(mathutil.RoundToString(0, 1)) //"0.0: - fmt.Println(mathutil.RoundToString(0.124, 2)) //"0.12" - fmt.Println(mathutil.RoundToString(0.125, 2)) //"0.13" - fmt.Println(mathutil.RoundToString(0.125, 3)) //"0.125" + fmt.Println(mathutil.RoundToString(0, 0)) //"0" + fmt.Println(mathutil.RoundToString(0, 1)) //"0.0: + fmt.Println(mathutil.RoundToString(0.124, 2)) //"0.12" + fmt.Println(mathutil.RoundToString(0.125, 2)) //"0.13" + fmt.Println(mathutil.RoundToString(0.125, 3)) //"0.125" } ``` - - ### TruncRound +截短n位小数(不进行四舍五入)
函数签名: @@ -211,6 +212,7 @@ func main() { ```go func TruncRound(x float64, n int) float64 ``` + 例子: ```go @@ -222,13 +224,10 @@ import ( ) func main() { - fmt.Println(mathutil.TruncRound(0, 0)) //0 - fmt.Println(mathutil.TruncRound(0, 1)) //0 - fmt.Println(mathutil.TruncRound(0.124, 2)) //0.12 - fmt.Println(mathutil.TruncRound(0.125, 2)) //0.12 - fmt.Println(mathutil.TruncRound(0.125, 3)) //0.125 + fmt.Println(mathutil.TruncRound(0, 0)) //0 + fmt.Println(mathutil.TruncRound(0, 1)) //0 + fmt.Println(mathutil.TruncRound(0.124, 2)) //0.12 + fmt.Println(mathutil.TruncRound(0.125, 2)) //0.12 + fmt.Println(mathutil.TruncRound(0.125, 3)) //0.125 } ``` - - - diff --git a/docs/netutil.md b/docs/netutil.md index 9fead53..7057a65 100644 --- a/docs/netutil.md +++ b/docs/netutil.md @@ -1,4 +1,5 @@ # Netutil + Package netutil contains functions to get net information and send http request. @@ -14,6 +15,7 @@ Package netutil contains functions to get net information and send http request. ## Usage: + ```go import ( "github.com/duke-git/lancet/netutil" @@ -23,33 +25,34 @@ import ( ## Index -- [ConvertMapToQueryString](#ConvertMapToQueryString) -- [EncodeUrl](#EncodeUrl) -- [GetInternalIp](#GetInternalIp) -- [GetIps](#GetIps) -- [GetMacAddrs](#GetMacAddrs) -- [GetPublicIpInfo](#GetPublicIpInfo) -- [GetRequestPublicIp](#GetRequestPublicIp) -- [IsPublicIP](#IsPublicIP) -- [IsInternalIP](#IsInternalIP) -- [HttpRequest](#HttpRequest) -- [HttpClient](#HttpClient) -- [SendRequest](#SendRequest) -- [DecodeResponse](#DecodeResponse) -- [StructToUrlValues](#StructToUrlValues) -- [HttpGetDeprecated](#HttpGet) -- [HttpDeleteDeprecated](#HttpDelete) -- [HttpPostDeprecated](#HttpPost) -- [HttpPutDeprecated](#HttpPut) -- [HttpPatchDeprecated](#HttpPatch) -- [ParseHttpResponse](#ParseHttpResponse) + +- [ConvertMapToQueryString](#ConvertMapToQueryString) +- [EncodeUrl](#EncodeUrl) +- [GetInternalIp](#GetInternalIp) +- [GetIps](#GetIps) +- [GetMacAddrs](#GetMacAddrs) +- [GetPublicIpInfo](#GetPublicIpInfo) +- [GetRequestPublicIp](#GetRequestPublicIp) +- [IsPublicIP](#IsPublicIP) +- [IsInternalIP](#IsInternalIP) +- [HttpRequest](#HttpRequest) +- [HttpClient](#HttpClient) +- [SendRequest](#SendRequest) +- [DecodeResponse](#DecodeResponse) +- [StructToUrlValues](#StructToUrlValues) +- [HttpGetDeprecated](#HttpGet) +- [HttpDeleteDeprecated](#HttpDelete) +- [HttpPostDeprecated](#HttpPost) +- [HttpPutDeprecated](#HttpPut) +- [HttpPatchDeprecated](#HttpPatch) +- [ParseHttpResponse](#ParseHttpResponse) ## Documentation - ### ConvertMapToQueryString +Convert map to url query string.
Signature: @@ -57,6 +60,7 @@ import ( ```go func ConvertMapToQueryString(param map[string]interface{}) string ``` + Example: ```go @@ -68,20 +72,19 @@ import ( ) func main() { - var m = map[string]interface{}{ - "c": 3, - "a": 1, - "b": 2, - } - qs := netutil.ConvertMapToQueryString(m) + var m = map[string]interface{}{ + "c": 3, + "a": 1, + "b": 2, + } + qs := netutil.ConvertMapToQueryString(m) - fmt.Println(qs) //a=1&b=2&c=3 + fmt.Println(qs) //a=1&b=2&c=3 } ``` - - ### EncodeUrl +Encode url query string values.
Signature: @@ -89,6 +92,7 @@ func main() { ```go func EncodeUrl(urlStr string) (string, error) ``` + Example: ```go @@ -100,17 +104,17 @@ import ( ) func main() { - urlAddr := "http://www.lancet.com?a=1&b=[2]" - encodedUrl, err := netutil.EncodeUrl(urlAddr) - if err != nil { - fmt.Println(err) - } - fmt.Println(encodedUrl) //http://www.lancet.com?a=1&b=%5B2%5D + urlAddr := "http://www.lancet.com?a=1&b=[2]" + encodedUrl, err := netutil.EncodeUrl(urlAddr) + if err != nil { + fmt.Println(err) + } + fmt.Println(encodedUrl) //http://www.lancet.com?a=1&b=%5B2%5D } ``` - ### GetInternalIp +Get internal ip information.
Signature: @@ -118,6 +122,7 @@ func main() { ```go func GetInternalIp() string ``` + Example: ```go @@ -125,21 +130,20 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - internalIp := netutil.GetInternalIp() - ip := net.ParseIP(internalIp) + internalIp := netutil.GetInternalIp() + ip := net.ParseIP(internalIp) - fmt.Println(ip) //192.168.1.9 + fmt.Println(ip) //192.168.1.9 } ``` - - ### GetIps +Get all ipv4 list.
Signature: @@ -147,6 +151,7 @@ func main() { ```go func GetIps() []string ``` + Example: ```go @@ -154,19 +159,18 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - ips := netutil.GetIps() - fmt.Println(ips) //[192.168.1.9] + ips := netutil.GetIps() + fmt.Println(ips) //[192.168.1.9] } ``` - - ### GetMacAddrs +Get all mac addresses list.
Signature: @@ -174,6 +178,7 @@ func main() { ```go func GetMacAddrs() []string { ``` + Example: ```go @@ -181,19 +186,18 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - addrs := netutil.GetMacAddrs() - fmt.Println(addrs) + addrs := netutil.GetMacAddrs() + fmt.Println(addrs) } ``` - - ### GetPublicIpInfo +Get public ip information.
Signature: @@ -201,20 +205,21 @@ func main() { ```go func GetPublicIpInfo() (*PublicIpInfo, error) type PublicIpInfo struct { - Status string `json:"status"` - Country string `json:"country"` - CountryCode string `json:"countryCode"` - Region string `json:"region"` - RegionName string `json:"regionName"` - City string `json:"city"` - Lat float64 `json:"lat"` - Lon float64 `json:"lon"` - Isp string `json:"isp"` - Org string `json:"org"` - As string `json:"as"` - Ip string `json:"query"` + Status string `json:"status"` + Country string `json:"country"` + CountryCode string `json:"countryCode"` + Region string `json:"region"` + RegionName string `json:"regionName"` + City string `json:"city"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Isp string `json:"isp"` + Org string `json:"org"` + As string `json:"as"` + Ip string `json:"query"` } ``` + Example: ```go @@ -226,17 +231,17 @@ import ( ) func main() { - publicIpInfo, err := netutil.GetPublicIpInfo() - if err != nil { - fmt.Println(err) - } + publicIpInfo, err := netutil.GetPublicIpInfo() + if err != nil { + fmt.Println(err) + } - fmt.Println(publicIpInfo) + fmt.Println(publicIpInfo) } ``` - ### GetRequestPublicIp +Get http request public ip.
Signature: @@ -244,6 +249,7 @@ func main() { ```go func GetRequestPublicIp(req *http.Request) string ``` + Example: ```go @@ -255,31 +261,30 @@ import ( ) func main() { - ip := "36.112.24.10" + ip := "36.112.24.10" - request1 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Forwarded-For": {ip}, - }, - } - publicIp1 := netutil.GetRequestPublicIp(&request1) - fmt.Println(publicIp1) //36.112.24.10 + request1 := http.Request{ + Method: "GET", + Header: http.Header{ + "X-Forwarded-For": {ip}, + }, + } + publicIp1 := netutil.GetRequestPublicIp(&request1) + fmt.Println(publicIp1) //36.112.24.10 - request2 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Real-Ip": {ip}, - }, - } - publicIp2 := netutil.GetRequestPublicIp(&request2) - fmt.Println(publicIp2) //36.112.24.10 + request2 := http.Request{ + Method: "GET", + Header: http.Header{ + "X-Real-Ip": {ip}, + }, + } + publicIp2 := netutil.GetRequestPublicIp(&request2) + fmt.Println(publicIp2) //36.112.24.10 } ``` - - ### IsPublicIP +Checks if a ip is public or not.
Signature: @@ -287,6 +292,7 @@ func main() { ```go func IsPublicIP(IP net.IP) bool ``` + Example: ```go @@ -294,22 +300,21 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - ip1 := net.ParseIP("192.168.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := net.ParseIP("192.168.0.1") + ip2 := net.ParseIP("36.112.24.10") - fmt.Println(netutil.IsPublicIP(ip1)) //false - fmt.Println(netutil.IsPublicIP(ip2)) //true + fmt.Println(netutil.IsPublicIP(ip1)) //false + fmt.Println(netutil.IsPublicIP(ip2)) //true } ``` - - ### IsInternalIP +Checks if an ip is intranet or not.
Signature: @@ -317,6 +322,7 @@ func main() { ```go func IsInternalIP(IP net.IP) bool ``` + Example: ```go @@ -324,36 +330,36 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - ip1 := net.ParseIP("127.0.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := net.ParseIP("127.0.0.1") + ip2 := net.ParseIP("36.112.24.10") - fmt.Println(netutil.IsInternalIP(ip1)) //true - fmt.Println(netutil.IsInternalIP(ip2)) //false + fmt.Println(netutil.IsInternalIP(ip1)) //true + fmt.Println(netutil.IsInternalIP(ip2)) //false } ``` - - ### HttpRequest +HttpRequest is a struct used to abstract HTTP request entity.
Signature: ```go type HttpRequest struct { - RawURL string - Method string - Headers http.Header - QueryParams url.Values - FormData url.Values - Body []byte + RawURL string + Method string + Headers http.Header + QueryParams url.Values + FormData url.Values + Body []byte } ``` + Example: ```go @@ -361,48 +367,48 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - header := http.Header{} - header.Add("Content-Type", "multipart/form-data") + header := http.Header{} + header.Add("Content-Type", "multipart/form-data") - postData := url.Values{} - postData.Add("userId", "1") - postData.Add("title", "testItem") + postData := url.Values{} + postData.Add("userId", "1") + postData.Add("title", "testItem") - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos", - Method: "POST", - Headers: header, - FormData: postData, - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos", + Method: "POST", + Headers: header, + FormData: postData, + } } ``` - ### HttpClient +HttpClient is a struct used to send HTTP request. It can be instanced with some configurations or none config.
Signature: ```go type HttpClient struct { - *http.Client - TLS *tls.Config - Request *http.Request - Config HttpClientConfig + *http.Client + TLS *tls.Config + Request *http.Request + Config HttpClientConfig } type HttpClientConfig struct { - SSLEnabled bool - TLSConfig *tls.Config - Compressed bool - HandshakeTimeout time.Duration - ResponseTimeout time.Duration - Verbose bool + SSLEnabled bool + TLSConfig *tls.Config + Compressed bool + HandshakeTimeout time.Duration + ResponseTimeout time.Duration + Verbose bool } func NewHttpClient() *HttpClient @@ -410,6 +416,7 @@ func NewHttpClient() *HttpClient func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient ``` + Example: ```go @@ -417,23 +424,22 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/netutil" ) func main() { - httpClientCfg := netutil.HttpClientConfig{ - SSLEnabled: true, - HandshakeTimeout:10 * time.Second - } - httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) + httpClientCfg := netutil.HttpClientConfig{ + SSLEnabled: true, + HandshakeTimeout:10 * time.Second + } + httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) } ``` - - ### SendRequest +Use HttpClient to send HTTP request.
Signature: @@ -441,6 +447,7 @@ func main() { ```go func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error) ``` + Example: ```go @@ -448,40 +455,39 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + log.Fatal(err) + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + httpClient.DecodeResponse(resp, &todo) - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) //1 } ``` - - ### DecodeResponse +Decode http response into target object.
Signature: @@ -489,6 +495,7 @@ func main() { ```go func (client *HttpClient) DecodeResponse(resp *http.Response, target interface{}) error ``` + Example: ```go @@ -496,39 +503,39 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + log.Fatal(err) + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + httpClient.DecodeResponse(resp, &todo) - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) //1 } ``` - ### StructToUrlValues +Convert struct to url values, only convert the field which is exported and has `json` tag.
Signature: @@ -536,6 +543,7 @@ func main() { ```go func StructToUrlValues(targetStruct interface{}) url.Values ``` + Example: ```go @@ -547,23 +555,23 @@ import ( ) func main() { - type TodoQuery struct { - Id int `json:"id"` - UserId int `json:"userId"` - } - todoQuery := TodoQuery{ - Id: 1, - UserId: 2, - } - todoValues := netutil.StructToUrlValues(todoQuery) + type TodoQuery struct { + Id int `json:"id"` + UserId int `json:"userId"` + } + todoQuery := TodoQuery{ + Id: 1, + UserId: 2, + } + todoValues := netutil.StructToUrlValues(todoQuery) - fmt.Println(todoValues.Get("id")) //1 - fmt.Println(todoValues.Get("userId")) //2 + fmt.Println(todoValues.Get("id")) //1 + fmt.Println(todoValues.Get("userId")) //2 } ``` - ### HttpGet (Deprecated: use SendRequest for replacement) +Send http get request.
Signature: @@ -575,6 +583,7 @@ func main() { // params[3] is http client which type should be http.Client. func HttpGet(url string, params ...interface{}) (*http.Response, error) ``` + Example: ```go @@ -582,30 +591,29 @@ package main import ( "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPost (Deprecated: use SendRequest for replacement) +Send http post request.
Signature: @@ -617,44 +625,44 @@ func main() { // params[3] is http client which type should be http.Client. func HttpPost(url string, params ...interface{}) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, "TestAddToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, "TestAddToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPost(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPost(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPut (Deprecated: use SendRequest for replacement) +Send http put request.
Signature: @@ -666,45 +674,45 @@ func main() { // params[3] is http client which type should be http.Client. func HttpPut(url string, params ...interface{}) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPutToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPutToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPut(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPut(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpDelete (Deprecated: use SendRequest for replacement) +Send http delete request.
Signature: @@ -716,34 +724,34 @@ func main() { // params[3] is http client which type should be http.Client. func HttpDelete(url string, params ...interface{}) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - resp, err := netutil.HttpDelete(url) - if err != nil { - log.Fatal(err) - } + url := "https://jsonplaceholder.typicode.com/todos/1" + resp, err := netutil.HttpDelete(url) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPatch (Deprecated: use SendRequest for replacement) +Send http patch request.
Signature: @@ -755,45 +763,45 @@ func main() { // params[3] is http client which type should be http.Client. func HttpPatch(url string, params ...interface{}) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPatchToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPatchToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPatch(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPatch(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### ParseHttpResponse +Decode http response to specified interface.
Signature: @@ -801,44 +809,44 @@ func main() { ```go func ParseHttpResponse(resp *http.Response, obj interface{}) error ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - toDoResp := &Todo{} - err = netutil.ParseHttpResponse(resp, toDoResp) - if err != nil { - log.Fatal(err) - } + toDoResp := &Todo{} + err = netutil.ParseHttpResponse(resp, toDoResp) + if err != nil { + log.Fatal(err) + } - fmt.Println(toDoResp) + fmt.Println(toDoResp) } ``` - diff --git a/docs/netutil_zh-CN.md b/docs/netutil_zh-CN.md index 31414a9..ad6c4e1 100644 --- a/docs/netutil_zh-CN.md +++ b/docs/netutil_zh-CN.md @@ -1,5 +1,6 @@ # Netutil -netutil网络包支持获取ip地址,发送http请求。 + +netutil 网络包支持获取 ip 地址,发送 http 请求。 @@ -13,6 +14,7 @@ netutil网络包支持获取ip地址,发送http请求。 ## 用法: + ```go import ( "github.com/duke-git/lancet/netutil" @@ -22,33 +24,34 @@ import ( ## 目录 -- [ConvertMapToQueryString](#ConvertMapToQueryString) -- [EncodeUrl](#EncodeUrl) -- [GetInternalIp](#GetInternalIp) -- [GetIps](#GetIps) -- [GetMacAddrs](#GetMacAddrs) -- [GetPublicIpInfo](#GetPublicIpInfo) -- [GetRequestPublicIp](#GetRequestPublicIp) -- [IsPublicIP](#IsPublicIP) -- [IsInternalIP](#IsInternalIP) -- [HttpRequest](#HttpRequest) -- [HttpClient](#HttpClient) -- [SendRequest](#SendRequest) -- [DecodeResponse](#DecodeResponse) -- [StructToUrlValues](#StructToUrlValues) -- [HttpGetDeprecated](#HttpGet) -- [HttpDeleteDeprecated](#HttpDelete) -- [HttpPostDeprecated](#HttpPost) -- [HttpPutDeprecated](#HttpPut) -- [HttpPatchDeprecated](#HttpPatch) -- [ParseHttpResponse](#ParseHttpResponse) + +- [ConvertMapToQueryString](#ConvertMapToQueryString) +- [EncodeUrl](#EncodeUrl) +- [GetInternalIp](#GetInternalIp) +- [GetIps](#GetIps) +- [GetMacAddrs](#GetMacAddrs) +- [GetPublicIpInfo](#GetPublicIpInfo) +- [GetRequestPublicIp](#GetRequestPublicIp) +- [IsPublicIP](#IsPublicIP) +- [IsInternalIP](#IsInternalIP) +- [HttpRequest](#HttpRequest) +- [HttpClient](#HttpClient) +- [SendRequest](#SendRequest) +- [DecodeResponse](#DecodeResponse) +- [StructToUrlValues](#StructToUrlValues) +- [HttpGetDeprecated](#HttpGet) +- [HttpDeleteDeprecated](#HttpDelete) +- [HttpPostDeprecated](#HttpPost) +- [HttpPutDeprecated](#HttpPut) +- [HttpPatchDeprecated](#HttpPatch) +- [ParseHttpResponse](#ParseHttpResponse) ## 文档 - ### ConvertMapToQueryString +将map转换成http查询字符串.
函数签名: @@ -56,6 +59,7 @@ import ( ```go func ConvertMapToQueryString(param map[string]interface{}) string ``` + 例子: ```go @@ -67,20 +71,19 @@ import ( ) func main() { - var m = map[string]interface{}{ - "c": 3, - "a": 1, - "b": 2, - } - qs := netutil.ConvertMapToQueryString(m) + var m = map[string]interface{}{ + "c": 3, + "a": 1, + "b": 2, + } + qs := netutil.ConvertMapToQueryString(m) - fmt.Println(qs) //a=1&b=2&c=3 + fmt.Println(qs) //a=1&b=2&c=3 } ``` - - ### EncodeUrl +编码url query string的值
函数签名: @@ -88,6 +91,7 @@ func main() { ```go func EncodeUrl(urlStr string) (string, error) ``` + 例子: ```go @@ -99,18 +103,17 @@ import ( ) func main() { - urlAddr := "http://www.lancet.com?a=1&b=[2]" - encodedUrl, err := netutil.EncodeUrl(urlAddr) - if err != nil { - fmt.Println(err) - } - fmt.Println(encodedUrl) //http://www.lancet.com?a=1&b=%5B2%5D + urlAddr := "http://www.lancet.com?a=1&b=[2]" + encodedUrl, err := netutil.EncodeUrl(urlAddr) + if err != nil { + fmt.Println(err) + } + fmt.Println(encodedUrl) //http://www.lancet.com?a=1&b=%5B2%5D } ``` - - ### GetInternalIp +获取内部ip
函数签名: @@ -118,6 +121,7 @@ func main() { ```go func GetInternalIp() string ``` + 例子: ```go @@ -125,20 +129,20 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - internalIp := netutil.GetInternalIp() - ip := net.ParseIP(internalIp) + internalIp := netutil.GetInternalIp() + ip := net.ParseIP(internalIp) - fmt.Println(ip) //192.168.1.9 + fmt.Println(ip) //192.168.1.9 } ``` - ### GetIps +获取ipv4地址列表
函数签名: @@ -146,6 +150,7 @@ func main() { ```go func GetIps() []string ``` + 例子: ```go @@ -153,19 +158,18 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - ips := netutil.GetIps() - fmt.Println(ips) //[192.168.1.9] + ips := netutil.GetIps() + fmt.Println(ips) //[192.168.1.9] } ``` - - ### GetMacAddrs +获取mac地址列
函数签名: @@ -173,6 +177,7 @@ func main() { ```go func GetMacAddrs() []string { ``` + 例子: ```go @@ -180,19 +185,18 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - addrs := netutil.GetMacAddrs() - fmt.Println(addrs) + addrs := netutil.GetMacAddrs() + fmt.Println(addrs) } ``` - - ### GetPublicIpInfo +获取公网ip信息
函数签名: @@ -200,20 +204,21 @@ func main() { ```go func GetPublicIpInfo() (*PublicIpInfo, error) type PublicIpInfo struct { - Status string `json:"status"` - Country string `json:"country"` - CountryCode string `json:"countryCode"` - Region string `json:"region"` - RegionName string `json:"regionName"` - City string `json:"city"` - Lat float64 `json:"lat"` - Lon float64 `json:"lon"` - Isp string `json:"isp"` - Org string `json:"org"` - As string `json:"as"` - Ip string `json:"query"` + Status string `json:"status"` + Country string `json:"country"` + CountryCode string `json:"countryCode"` + Region string `json:"region"` + RegionName string `json:"regionName"` + City string `json:"city"` + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + Isp string `json:"isp"` + Org string `json:"org"` + As string `json:"as"` + Ip string `json:"query"` } ``` + 例子: ```go @@ -225,18 +230,17 @@ import ( ) func main() { - publicIpInfo, err := netutil.GetPublicIpInfo() - if err != nil { - fmt.Println(err) - } + publicIpInfo, err := netutil.GetPublicIpInfo() + if err != nil { + fmt.Println(err) + } - fmt.Println(publicIpInfo) + fmt.Println(publicIpInfo) } ``` - - ### GetRequestPublicIp +获取http请求ip
函数签名: @@ -244,6 +248,7 @@ func main() { ```go func GetRequestPublicIp(req *http.Request) string ``` + 例子: ```go @@ -255,31 +260,30 @@ import ( ) func main() { - ip := "36.112.24.10" + ip := "36.112.24.10" - request1 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Forwarded-For": {ip}, - }, - } - publicIp1 := netutil.GetRequestPublicIp(&request1) - fmt.Println(publicIp1) //36.112.24.10 + request1 := http.Request{ + Method: "GET", + Header: http.Header{ + "X-Forwarded-For": {ip}, + }, + } + publicIp1 := netutil.GetRequestPublicIp(&request1) + fmt.Println(publicIp1) //36.112.24.10 - request2 := http.Request{ - Method: "GET", - Header: http.Header{ - "X-Real-Ip": {ip}, - }, - } - publicIp2 := netutil.GetRequestPublicIp(&request2) - fmt.Println(publicIp2) //36.112.24.10 + request2 := http.Request{ + Method: "GET", + Header: http.Header{ + "X-Real-Ip": {ip}, + }, + } + publicIp2 := netutil.GetRequestPublicIp(&request2) + fmt.Println(publicIp2) //36.112.24.10 } ``` - - ### IsPublicIP +判断ip是否是公共ip
函数签名: @@ -287,6 +291,7 @@ func main() { ```go func IsPublicIP(IP net.IP) bool ``` + 例子: ```go @@ -294,22 +299,21 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - ip1 := net.ParseIP("192.168.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := net.ParseIP("192.168.0.1") + ip2 := net.ParseIP("36.112.24.10") - fmt.Println(netutil.IsPublicIP(ip1)) //false - fmt.Println(netutil.IsPublicIP(ip2)) //true + fmt.Println(netutil.IsPublicIP(ip1)) //false + fmt.Println(netutil.IsPublicIP(ip2)) //true } ``` - - ### IsInternalIP +判断ip是否是局域网ip.
函数签名: @@ -317,6 +321,7 @@ func main() { ```go func IsInternalIP(IP net.IP) bool ``` + 例子: ```go @@ -324,35 +329,36 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - ip1 := net.ParseIP("127.0.0.1") - ip2 := net.ParseIP("36.112.24.10") + ip1 := net.ParseIP("127.0.0.1") + ip2 := net.ParseIP("36.112.24.10") - fmt.Println(netutil.IsInternalIP(ip1)) //true - fmt.Println(netutil.IsInternalIP(ip2)) //false + fmt.Println(netutil.IsInternalIP(ip1)) //true + fmt.Println(netutil.IsInternalIP(ip2)) //false } ``` - ### HttpRequest +HttpRequest用于抽象HTTP请求实体的结构
函数签名: ```go type HttpRequest struct { - RawURL string - Method string - Headers http.Header - QueryParams url.Values - FormData url.Values - Body []byte + RawURL string + Method string + Headers http.Header + QueryParams url.Values + FormData url.Values + Body []byte } ``` + 例子: ```go @@ -360,48 +366,48 @@ package main import ( "fmt" - "net" + "net" "github.com/duke-git/lancet/netutil" ) func main() { - header := http.Header{} - header.Add("Content-Type", "multipart/form-data") + header := http.Header{} + header.Add("Content-Type", "multipart/form-data") - postData := url.Values{} - postData.Add("userId", "1") - postData.Add("title", "testItem") + postData := url.Values{} + postData.Add("userId", "1") + postData.Add("title", "testItem") - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos", - Method: "POST", - Headers: header, - FormData: postData, - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos", + Method: "POST", + Headers: header, + FormData: postData, + } } ``` - ### HttpClient +HttpClient是用于发送HTTP请求的结构体。它可以用一些配置参数或无配置实例化.
函数签名: ```go type HttpClient struct { - *http.Client - TLS *tls.Config - Request *http.Request - Config HttpClientConfig + *http.Client + TLS *tls.Config + Request *http.Request + Config HttpClientConfig } type HttpClientConfig struct { - SSLEnabled bool - TLSConfig *tls.Config - Compressed bool - HandshakeTimeout time.Duration - ResponseTimeout time.Duration - Verbose bool + SSLEnabled bool + TLSConfig *tls.Config + Compressed bool + HandshakeTimeout time.Duration + ResponseTimeout time.Duration + Verbose bool } func NewHttpClient() *HttpClient @@ -409,6 +415,7 @@ func NewHttpClient() *HttpClient func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient ``` + 例子: ```go @@ -416,23 +423,22 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/netutil" ) func main() { - httpClientCfg := netutil.HttpClientConfig{ - SSLEnabled: true, - HandshakeTimeout:10 * time.Second - } - httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) + httpClientCfg := netutil.HttpClientConfig{ + SSLEnabled: true, + HandshakeTimeout:10 * time.Second + } + httpClient := netutil.NewHttpClientWithConfig(&httpClientCfg) } ``` - - ### SendRequest +HttpClient发送http请求
函数签名: @@ -440,6 +446,7 @@ func main() { ```go func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, error) ``` + 例子: ```go @@ -447,40 +454,39 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + log.Fatal(err) + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + httpClient.DecodeResponse(resp, &todo) - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) //1 } ``` - - ### DecodeResponse +解析http响应体到目标结构体
函数签名: @@ -488,6 +494,7 @@ func main() { ```go func (client *HttpClient) DecodeResponse(resp *http.Response, target interface{}) error ``` + 例子: ```go @@ -495,39 +502,39 @@ package main import ( "fmt" - "net" - "time" + "net" + "time" "github.com/duke-git/lancet/netutil" ) func main() { - request := &netutil.HttpRequest{ - RawURL: "https://jsonplaceholder.typicode.com/todos/1", - Method: "GET", - } + request := &netutil.HttpRequest{ + RawURL: "https://jsonplaceholder.typicode.com/todos/1", + Method: "GET", + } - httpClient := netutil.NewHttpClient() - resp, err := httpClient.SendRequest(request) - if err != nil || resp.StatusCode != 200 { - log.Fatal(err) - } + httpClient := netutil.NewHttpClient() + resp, err := httpClient.SendRequest(request) + if err != nil || resp.StatusCode != 200 { + log.Fatal(err) + } - type Todo struct { - UserId int `json:"userId"` - Id int `json:"id"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + UserId int `json:"userId"` + Id int `json:"id"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - var todo Todo - httpClient.DecodeResponse(resp, &todo) + var todo Todo + httpClient.DecodeResponse(resp, &todo) - fmt.Println(todo.Id) //1 + fmt.Println(todo.Id) //1 } ``` - ### StructToUrlValues +将结构体转为url values, 仅转化结构体导出字段并且包含`json` tag.
函数签名: @@ -535,6 +542,7 @@ func main() { ```go func StructToUrlValues(targetStruct interface{}) url.Values ``` + 例子: ```go @@ -546,24 +554,23 @@ import ( ) func main() { - type TodoQuery struct { - Id int `json:"id"` - UserId int `json:"userId"` - } - todoQuery := TodoQuery{ - Id: 1, - UserId: 2, - } - todoValues := netutil.StructToUrlValues(todoQuery) + type TodoQuery struct { + Id int `json:"id"` + UserId int `json:"userId"` + } + todoQuery := TodoQuery{ + Id: 1, + UserId: 2, + } + todoValues := netutil.StructToUrlValues(todoQuery) - fmt.Println(todoValues.Get("id")) //1 - fmt.Println(todoValues.Get("userId")) //2 + fmt.Println(todoValues.Get("id")) //1 + fmt.Println(todoValues.Get("userId")) //2 } ``` - - ### HttpGet (Deprecated: use SendRequest for replacement) +发送http get请求
函数签名: @@ -575,6 +582,7 @@ func main() { // params[3] http client,类型必须是http.Client func HttpGet(url string, params ...interface{}) (*http.Response, error) ``` + 例子: ```go @@ -582,30 +590,29 @@ package main import ( "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPost (Deprecated: use SendRequest for replacement) +发送http post请求
函数签名: @@ -617,44 +624,44 @@ func main() { // params[3] http client,类型必须是http.Client func HttpPost(url string, params ...interface{}) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, "TestAddToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, "TestAddToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPost(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPost(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPut (Deprecated: use SendRequest for replacement) +发送http put请求
函数签名: @@ -666,45 +673,45 @@ func main() { // params[3] http client,类型必须是http.Client func HttpPut(url string, params ...interface{}) (*http.Response, error) ``` + Example: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPutToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPutToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPut(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPut(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpDelete (Deprecated: use SendRequest for replacement) +发送http delete请求
函数签名: @@ -716,34 +723,34 @@ func main() { // params[3] http client,类型必须是http.Client func HttpDelete(url string, params ...interface{}) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - resp, err := netutil.HttpDelete(url) - if err != nil { - log.Fatal(err) - } + url := "https://jsonplaceholder.typicode.com/todos/1" + resp, err := netutil.HttpDelete(url) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### HttpPatch (Deprecated: use SendRequest for replacement) +发送http patch请求
函数签名: @@ -755,45 +762,45 @@ func main() { // params[3] http client,类型必须是http.Client func HttpPatch(url string, params ...interface{}) (*http.Response, error) ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - } - todo := Todo{1, 1, "TestPatchToDo"} - bodyParams, _ := json.Marshal(todo) + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + } + todo := Todo{1, 1, "TestPatchToDo"} + bodyParams, _ := json.Marshal(todo) - resp, err := netutil.HttpPatch(url, header, nil, bodyParams) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpPatch(url, header, nil, bodyParams) + if err != nil { + log.Fatal(err) + } - body, _ := ioutil.ReadAll(resp.Body) - fmt.Println(body) + body, _ := ioutil.ReadAll(resp.Body) + fmt.Println(body) } ``` - - ### ParseHttpResponse +将http请求响应解码成特定struct值
函数签名: @@ -801,44 +808,44 @@ func main() { ```go func ParseHttpResponse(resp *http.Response, obj interface{}) error ``` + 例子: ```go package main import ( - "encoding/json" + "encoding/json" "fmt" - "io/ioutil" - "log" + "io/ioutil" + "log" "github.com/duke-git/lancet/netutil" ) func main() { - url := "https://jsonplaceholder.typicode.com/todos/1" - header := map[string]string{ - "Content-Type": "application/json", - } + url := "https://jsonplaceholder.typicode.com/todos/1" + header := map[string]string{ + "Content-Type": "application/json", + } - resp, err := netutil.HttpGet(url, header) - if err != nil { - log.Fatal(err) - } + resp, err := netutil.HttpGet(url, header) + if err != nil { + log.Fatal(err) + } - type Todo struct { - Id int `json:"id"` - UserId int `json:"userId"` - Title string `json:"title"` - Completed bool `json:"completed"` - } + type Todo struct { + Id int `json:"id"` + UserId int `json:"userId"` + Title string `json:"title"` + Completed bool `json:"completed"` + } - toDoResp := &Todo{} - err = netutil.ParseHttpResponse(resp, toDoResp) - if err != nil { - log.Fatal(err) - } + toDoResp := &Todo{} + err = netutil.ParseHttpResponse(resp, toDoResp) + if err != nil { + log.Fatal(err) + } - fmt.Println(toDoResp) + fmt.Println(toDoResp) } ``` - diff --git a/docs/random.md b/docs/random.md index 555dbe5..b986df4 100644 --- a/docs/random.md +++ b/docs/random.md @@ -56,8 +56,8 @@ import ( ) func main() { - randBytes := random.RandBytes(4) - fmt.Println(randBytes) + randBytes := random.RandBytes(4) + fmt.Println(randBytes) } ``` @@ -82,8 +82,8 @@ import ( ) func main() { - rInt := random.RandInt(1, 10) - fmt.Println(rInt) + rInt := random.RandInt(1, 10) + fmt.Println(rInt) } ``` @@ -108,8 +108,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //pGWsze + randStr := random.RandString(6) + fmt.Println(randStr) //pGWsze } ``` @@ -134,8 +134,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //PACWGF + randStr := random.RandString(6) + fmt.Println(randStr) //PACWGF } ``` @@ -160,8 +160,8 @@ import ( ) func main() { - randStr := random.RandLower(6) - fmt.Println(randStr) //siqbew + randStr := random.RandLower(6) + fmt.Println(randStr) //siqbew } ``` @@ -186,8 +186,8 @@ import ( ) func main() { - randStr := random.RandNumeral(6) - fmt.Println(randStr) //035172 + randStr := random.RandNumeral(6) + fmt.Println(randStr) //035172 } ``` @@ -212,8 +212,8 @@ import ( ) func main() { - randStr := random.RandNumeralOrLetter(6) - fmt.Println(randStr) //0aW7cQ + randStr := random.RandNumeralOrLetter(6) + fmt.Println(randStr) //0aW7cQ } ``` @@ -238,10 +238,10 @@ import ( ) func main() { - uuid, err := random.UUIdV4() + uuid, err := random.UUIdV4() if err != nil { return } - fmt.Println(uuid) + fmt.Println(uuid) } ``` diff --git a/docs/random_zh-CN.md b/docs/random_zh-CN.md index 68df0d1..5c8fffd 100644 --- a/docs/random_zh-CN.md +++ b/docs/random_zh-CN.md @@ -56,8 +56,8 @@ import ( ) func main() { - randBytes := random.RandBytes(4) - fmt.Println(randBytes) + randBytes := random.RandBytes(4) + fmt.Println(randBytes) } ``` @@ -82,8 +82,8 @@ import ( ) func main() { - rInt := random.RandInt(1, 10) - fmt.Println(rInt) + rInt := random.RandInt(1, 10) + fmt.Println(rInt) } ``` @@ -108,8 +108,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //pGWsze + randStr := random.RandString(6) + fmt.Println(randStr) //pGWsze } ``` @@ -134,8 +134,8 @@ import ( ) func main() { - randStr := random.RandString(6) - fmt.Println(randStr) //PACWGF + randStr := random.RandString(6) + fmt.Println(randStr) //PACWGF } ``` @@ -160,8 +160,8 @@ import ( ) func main() { - randStr := random.RandLower(6) - fmt.Println(randStr) //siqbew + randStr := random.RandLower(6) + fmt.Println(randStr) //siqbew } ``` @@ -186,8 +186,8 @@ import ( ) func main() { - randStr := random.RandNumeral(6) - fmt.Println(randStr) //035172 + randStr := random.RandNumeral(6) + fmt.Println(randStr) //035172 } ``` @@ -212,8 +212,8 @@ import ( ) func main() { - randStr := random.RandNumeralOrLetter(6) - fmt.Println(randStr) //0aW7cQ + randStr := random.RandNumeralOrLetter(6) + fmt.Println(randStr) //0aW7cQ } ``` @@ -238,10 +238,10 @@ import ( ) func main() { - uuid, err := random.UUIdV4() + uuid, err := random.UUIdV4() if err != nil { return } - fmt.Println(uuid) + fmt.Println(uuid) } ``` diff --git a/docs/retry.md b/docs/retry.md index a0483c1..781bf38 100644 --- a/docs/retry.md +++ b/docs/retry.md @@ -1,4 +1,5 @@ # Retry + Package retry is for executing a function repeatedly until it was successful or canceled by the context. @@ -7,10 +8,10 @@ Package retry is for executing a function repeatedly until it was successful or [https://github.com/duke-git/lancet/blob/v1/retry/retry.go](https://github.com/duke-git/lancet/blob/v1/retry/retry.go) - ## Usage: + ```go import ( "github.com/duke-git/lancet/retry" @@ -20,18 +21,19 @@ import ( ## Index -- [Context](#Context) -- [Retry](#Retry) -- [RetryFunc](#RetryFunc) -- [RetryDuration](#RetryDuration) -- [RetryTimes](#RetryTimes) + +- [Context](#Context) +- [Retry](#Retry) +- [RetryFunc](#RetryFunc) +- [RetryDuration](#RetryDuration) +- [RetryTimes](#RetryTimes) ## Documentation - ### Context +Set retry context config, can cancel the retry with context.
Signature: @@ -39,43 +41,42 @@ import ( ```go func Context(ctx context.Context) ``` + Example: ```go import ( - "context" - "errors" - "fmt" - "github.com/duke-git/lancet/retry" - "time" + "context" + "errors" + "fmt" + "github.com/duke-git/lancet/retry" + "time" ) func main() { - ctx, cancel := context.WithCancel(context.TODO()) - var number int - increaseNumber := func() error { - number++ - if number > 3 { - cancel() - } - return errors.New("error occurs") - } + ctx, cancel := context.WithCancel(context.TODO()) + var number int + increaseNumber := func() error { + number++ + if number > 3 { + cancel() + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, - retry.RetryDuration(time.Microsecond*50), - retry.Context(ctx), - ) + err := retry.Retry(increaseNumber, + retry.RetryDuration(time.Microsecond*50), + retry.Context(ctx), + ) - if err != nil { - fmt.Println(err) //retry is cancelled - } + if err != nil { + fmt.Println(err) //retry is cancelled + } } ``` - - - ### RetryFunc +Function that retry executes.
Signature: @@ -83,6 +84,7 @@ func main() { ```go type RetryFunc func() error ``` + Example: ```go @@ -98,26 +100,25 @@ import ( func main() { var number int var increaseNumber retry.RetryFunc - increaseNumber = func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber = func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) if err != nil { - log.Fatal(err) - } + log.Fatal(err) + } fmt.Println(number) //3 } ``` - - ### RetryTimes +Set times of retry. Default times is 5.
Signature: @@ -125,6 +126,7 @@ func main() { ```go func RetryTimes(n uint) ``` + Example: ```go @@ -139,24 +141,23 @@ import ( func main() { var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryTimes(2)) + err := retry.Retry(increaseNumber, retry.RetryTimes(2)) if err != nil { - log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1 - } + log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1 + } } ``` - - ### RetryDuration +Set duration of retries. Default duration is 3 second.
Signature: @@ -164,6 +165,7 @@ func main() { ```go func RetryDuration(d time.Duration) ``` + Example: ```go @@ -178,25 +180,25 @@ import ( func main() { var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) if err != nil { - log.Fatal(err) - } + log.Fatal(err) + } fmt.Println(number) //3 } ``` - ### Retry +Executes the retryFunc repeatedly until it was successful or canceled by the context.
Signature: @@ -204,6 +206,7 @@ func main() { ```go func Retry(retryFunc RetryFunc, opts ...Option) error ``` + Example: ```go @@ -218,18 +221,18 @@ import ( func main() { var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) if err != nil { - log.Fatal(err) - } + log.Fatal(err) + } fmt.Println(number) //3 } diff --git a/docs/retry_zh-CN.md b/docs/retry_zh-CN.md index 5613f31..89073b2 100644 --- a/docs/retry_zh-CN.md +++ b/docs/retry_zh-CN.md @@ -1,5 +1,6 @@ # Retry -retry重试执行函数直到函数运行成功或被context cancel。 + +retry 重试执行函数直到函数运行成功或被 context cancel。 @@ -7,10 +8,10 @@ retry重试执行函数直到函数运行成功或被context cancel。 [https://github.com/duke-git/lancet/blob/v1/retry/retry.go](https://github.com/duke-git/lancet/blob/v1/retry/retry.go) - ## 用法: + ```go import ( "github.com/duke-git/lancet/retry" @@ -20,20 +21,19 @@ import ( ## 目录 -- [Context](#Context) -- [Retry](#Retry) -- [RetryFunc](#RetryFunc) -- [RetryDuration](#RetryDuration) -- [RetryTimes](#RetryTimes) +- [Context](#Context) +- [Retry](#Retry) +- [RetryFunc](#RetryFunc) +- [RetryDuration](#RetryDuration) +- [RetryTimes](#RetryTimes) - -## Document文档 - +## Document 文档 ### Context +设置重试context参数
函数签名: @@ -41,43 +41,42 @@ import ( ```go func Context(ctx context.Context) ``` + 例子: ```go import ( - "context" - "errors" - "fmt" - "lancet-demo/retry" - "time" + "context" + "errors" + "fmt" + "lancet-demo/retry" + "time" ) func main() { - ctx, cancel := context.WithCancel(context.TODO()) - var number int - increaseNumber := func() error { - number++ - if number > 3 { - cancel() - } - return errors.New("error occurs") - } + ctx, cancel := context.WithCancel(context.TODO()) + var number int + increaseNumber := func() error { + number++ + if number > 3 { + cancel() + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, - retry.RetryDuration(time.Microsecond*50), - retry.Context(ctx), - ) + err := retry.Retry(increaseNumber, + retry.RetryDuration(time.Microsecond*50), + retry.Context(ctx), + ) - if err != nil { - fmt.Println(err) //retry is cancelled - } + if err != nil { + fmt.Println(err) //retry is cancelled + } } ``` - - - ### RetryFunc +被重试执行的函数
函数签名: @@ -85,6 +84,7 @@ func main() { ```go type RetryFunc func() error ``` + 例子: ```go @@ -100,26 +100,25 @@ import ( func main() { var number int var increaseNumber retry.RetryFunc - increaseNumber = func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber = func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) if err != nil { - log.Fatal(err) - } + log.Fatal(err) + } fmt.Println(number) //3 } ``` - - ### RetryTimes +设置重试次数,默认5
函数签名: @@ -127,6 +126,7 @@ func main() { ```go func RetryTimes(n uint) ``` + 例子: ```go @@ -141,24 +141,23 @@ import ( func main() { var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryTimes(2)) + err := retry.Retry(increaseNumber, retry.RetryTimes(2)) if err != nil { - log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1 - } + log.Fatal(err) //2022/02/01 18:42:25 function main.main.func1 run failed after 2 times retry exit status 1 + } } ``` - - ### RetryDuration +设置重试间隔时间,默认3秒
函数签名: @@ -166,6 +165,7 @@ func main() { ```go func RetryDuration(d time.Duration) ``` + 例子: ```go @@ -180,25 +180,25 @@ import ( func main() { var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) if err != nil { - log.Fatal(err) - } + log.Fatal(err) + } fmt.Println(number) //3 } ``` - ### Retry +重试执行函数retryFunc,直到函数运行成功,或被context停止
函数签名: @@ -206,6 +206,7 @@ func main() { ```go func Retry(retryFunc RetryFunc, opts ...Option) error ``` + 例子: ```go @@ -220,18 +221,18 @@ import ( func main() { var number int - increaseNumber := func() error { - number++ - if number == 3 { - return nil - } - return errors.New("error occurs") - } + increaseNumber := func() error { + number++ + if number == 3 { + return nil + } + return errors.New("error occurs") + } - err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) + err := retry.Retry(increaseNumber, retry.RetryDuration(time.Microsecond*50)) if err != nil { - log.Fatal(err) - } + log.Fatal(err) + } fmt.Println(number) //3 } diff --git a/docs/slice.md b/docs/slice.md index cd6d072..867cee2 100644 --- a/docs/slice.md +++ b/docs/slice.md @@ -1,4 +1,5 @@ # Slice + Package slice implements some functions to manipulate slice. @@ -7,10 +8,10 @@ Package slice implements some functions to manipulate slice. [https://github.com/duke-git/lancet/blob/v1/slice/slice.go](https://github.com/duke-git/lancet/blob/v1/slice/slice.go) - ## Usage: + ```go import ( "github.com/duke-git/lancet/slice" @@ -20,57 +21,58 @@ import ( ## Index -- [AppendIfAbsent](#AppendIfAbsent) -- [Contain](#Contain) -- [ContainSubSlice](#ContainSubSlice) -- [Chunk](#Chunk) -- [Compact](#Compact) -- [Concat](#Concat) -- [Count](#Count) -- [Difference](#Difference) -- [DifferenceBy](#DifferenceBy) -- [DeleteByIndex](#DeleteByIndex) -- [Drop](#Drop) -- [Equal](#Equal) -- [EqualWith](#EqualWith) -- [Every](#Every) -- [Filter](#Filter) -- [Find](#Find) -- [FindLast](#FindLast) -- [FlattenDeep](#FlattenDeep) -- [ForEach](#ForEach) -- [GroupBy](#GroupBy) -- [IntSlice](#IntSlice) -- [InterfaceSlice](#InterfaceSlice) -- [Intersection](#Intersection) -- [InsertByIndex](#InsertByIndex) -- [IndexOf](#IndexOf) -- [LastIndexOf](#LastIndexOf) -- [Map](#Map) -- [ReverseSlice](#ReverseSlice) -- [Reduce](#Reduce) -- [Shuffle](#Shuffle) -- [SortByField](#SortByField) -- [Some](#Some) -- [StringSlice](#StringSlice) -- [ToSlice](#ToSlice) -- [ToSlicePointer](#ToSlicePointer) -- [Unique](#Unique) -- [UniqueBy](#UniqueBy) -- [Union](#Union) -- [UpdateByIndex](#UpdateByIndex) -- [Without](#Without) + +- [AppendIfAbsent](#AppendIfAbsent) +- [Contain](#Contain) +- [ContainSubSlice](#ContainSubSlice) +- [Chunk](#Chunk) +- [Compact](#Compact) +- [Concat](#Concat) +- [Count](#Count) +- [Difference](#Difference) +- [DifferenceBy](#DifferenceBy) +- [DeleteByIndex](#DeleteByIndex) +- [Drop](#Drop) +- [Equal](#Equal) +- [EqualWith](#EqualWith) +- [Every](#Every) +- [Filter](#Filter) +- [Find](#Find) +- [FindLast](#FindLast) +- [FlattenDeep](#FlattenDeep) +- [ForEach](#ForEach) +- [GroupBy](#GroupBy) +- [IntSlice](#IntSlice) +- [InterfaceSlice](#InterfaceSlice) +- [Intersection](#Intersection) +- [InsertByIndex](#InsertByIndex) +- [IndexOf](#IndexOf) +- [LastIndexOf](#LastIndexOf) +- [Map](#Map) +- [ReverseSlice](#ReverseSlice) +- [Reduce](#Reduce) +- [Shuffle](#Shuffle) +- [SortByField](#SortByField) +- [Some](#Some) +- [StringSlice](#StringSlice) +- [ToSlice](#ToSlice) +- [ToSlicePointer](#ToSlicePointer) +- [Unique](#Unique) +- [UniqueBy](#UniqueBy) +- [Union](#Union) +- [UpdateByIndex](#UpdateByIndex) +- [Without](#Without) ## Documentation ## Note: + 1. param which type is interface{} in below functions should be slice. - - ### AppendIfAbsent +If slice doesn't contain the value, append it to the slice.
Signature: @@ -78,26 +80,27 @@ import ( ```go func AppendIfAbsent(slice interface{}, value interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - strs := []string{"a", "b"} - res1 := slice.AppendIfAbsent(strs, "a") - fmt.Println(res1) //[]string{"a", "b"} + strs := []string{"a", "b"} + res1 := slice.AppendIfAbsent(strs, "a") + fmt.Println(res1) //[]string{"a", "b"} - res2 := slice.AppendIfAbsent(strs, "cannot") - fmt.Println(res2"} + res2 := slice.AppendIfAbsent(strs, "cannot") + fmt.Println(res2"} } ``` - ### Contain +Check if the value is in the slice or not. iterableType param can be string, map or slice.
Signature: @@ -105,22 +108,23 @@ func main() { ```go func Contain(iterableType interface{}, value interface{}) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Contain([]string{"a", "b", "c"}, "a") - fmt.Println(res) //true + res := slice.Contain([]string{"a", "b", "c"}, "a") + fmt.Println(res) //true } ``` - ### ContainSubSlice +Check if the slice contain subslice or not.
Signature: @@ -128,24 +132,23 @@ func main() { ```go func ContainSubSlice(slice interface{}, subslice interface{}) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) - fmt.Println(res) //true + res := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) + fmt.Println(res) //true } ``` - - - ### Chunk +Creates an slice of elements split into groups the length of `size`.
Signature: @@ -153,24 +156,24 @@ func main() { ```go func Chunk(slice []interface{}, size int) [][]interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := []string{"a", "b", "c", "d", "e"} - res := slice.Chunk(InterfaceSlice(arr), 3) - fmt.Println(res) //[][]interface{}{{"a", "b", "c"}, {"d", "e"}} + arr := []string{"a", "b", "c", "d", "e"} + res := slice.Chunk(InterfaceSlice(arr), 3) + fmt.Println(res) //[][]interface{}{{"a", "b", "c"}, {"d", "e"}} } ``` - - ### Compact +Creates an slice with all falsey values removed. The values false, nil, 0, and "" are falsey.
Signature: @@ -178,22 +181,23 @@ func main() { ```go func Compact(slice interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Compact([]int{0, 1, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + res := slice.Compact([]int{0, 1, 2, 3}) + fmt.Println(res) //[]int{1, 2, 3} } ``` - ### Concat +Creates a new slice concatenating slice with any additional slices and/or values.
Signature: @@ -201,26 +205,26 @@ func main() { ```go func Concat(slice interface{}, values ...interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res1 := slice.Concat([]int{1, 2, 3}, 4, 5) - fmt.Println(res1) //[]int{1, 2, 3, 4, 5} + res1 := slice.Concat([]int{1, 2, 3}, 4, 5) + fmt.Println(res1) //[]int{1, 2, 3, 4, 5} - res2 := slice.Concat([]int{1, 2, 3}, []int{4, 5}) - fmt.Println(res2) //[]int{1, 2, 3, 4, 5} + res2 := slice.Concat([]int{1, 2, 3}, []int{4, 5}) + fmt.Println(res2) //[]int{1, 2, 3, 4, 5} } ``` - - ### Count +Count iterates over elements of slice, returns a count of all matched elements. The function signature should be func(index int, value interface{}) bool.
Signature: @@ -228,29 +232,28 @@ func main() { ```go func Count(slice, function interface{}) int ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(i, num int) bool { - return (num % 2) == 0 - } + nums := []int{1, 2, 3, 4, 5, 6} + evenFunc := func(i, num int) bool { + return (num % 2) == 0 + } - res := slice.Count(nums, evenFunc) - fmt.Println(res) //3 + res := slice.Count(nums, evenFunc) + fmt.Println(res) //3 } ``` - - - ### Difference +Creates an slice of whose element not included in the other given slice.
Signature: @@ -258,27 +261,26 @@ func main() { ```go func Difference(slice1, slice2 interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6} - res := slice.Difference(s1, s2) - fmt.Println(res) //[]int{1, 2, 3} + res := slice.Difference(s1, s2) + fmt.Println(res) //[]int{1, 2, 3} } ``` - - - ### DifferenceBy +DifferenceBy accepts iteratee func which is invoked for each element of slice and values to generate the criterion by which they're compared.
Signature: @@ -286,30 +288,29 @@ func main() { ```go func DifferenceBy(slice interface{}, comparedSlice interface{}, iterateeFn interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} - addOne := func(i int, v int) int { - return v + 1 - } + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6} + addOne := func(i int, v int) int { + return v + 1 + } - res := slice.DifferenceBy(s1, s2, addOne) - fmt.Println(res) //[]int{1, 2} + res := slice.DifferenceBy(s1, s2, addOne) + fmt.Println(res) //[]int{1, 2} } ``` - - - ### DeleteByIndex +Delete the element of slice from start index to end index - 1.
Signature: @@ -317,28 +318,27 @@ func main() { ```go func DeleteByIndex(slice interface{}, start int, end ...int) (interface{}, error) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res1 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 3) - fmt.Println(res1) //[]string{"a", "b", "c", "e"} + res1 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 3) + fmt.Println(res1) //[]string{"a", "b", "c", "e"} - res2 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 0, 2) - fmt.Println(res2) //[]string{"c", "d", "e"} + res2 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 0, 2) + fmt.Println(res2) //[]string{"c", "d", "e"} } ``` - - - ### Drop +Creates a slice with `n` elements dropped from the beginning when n > 0, or `n` elements dropped from the ending when n < 0.
Signature: @@ -346,29 +346,29 @@ func main() { ```go func Drop(slice interface{}, n int) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res1 := slice.Drop([]int{}, 0) - fmt.Println(res1) //[]int{} + res1 := slice.Drop([]int{}, 0) + fmt.Println(res1) //[]int{} - res2 := slice.Drop([]int{1, 2, 3, 4, 5}, 1) - fmt.Println(res2) //[]int{2, 3, 4, 5} + res2 := slice.Drop([]int{1, 2, 3, 4, 5}, 1) + fmt.Println(res2) //[]int{2, 3, 4, 5} - res3 := slice.Drop([]int{1, 2, 3, 4, 5}, -1) - fmt.Println(res3) //[]int{1, 2, 3, 4} + res3 := slice.Drop([]int{1, 2, 3, 4, 5}, -1) + fmt.Println(res3) //[]int{1, 2, 3, 4} } ``` - - ### Equal +Check if two slices are equal: the same length and all elements' order and value are equal.
Signature: @@ -376,30 +376,30 @@ func main() { ```go func Equal(slice1, slice2 interface{}) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{1, 2, 3} - slice3 := []int{3, 2, 1} + slice1 := []int{1, 2, 3} + slice2 := []int{1, 2, 3} + slice3 := []int{3, 2, 1} - res1 := slice.Equal(slice1, slice2) - res2 := slice.Equal(slice1, slice3) + res1 := slice.Equal(slice1, slice2) + res2 := slice.Equal(slice1, slice3) - fmt.Println(res1) //true - fmt.Println(res2) //false + fmt.Println(res1) //true + fmt.Println(res2) //false } ``` - - ### EqualWith +Check if two slices are equal with comparator funcation.comparator signature: func(a interface{}, b interface{}) bool
Signature: @@ -407,31 +407,31 @@ func main() { ```go func EqualWith(slice1, slice2 interface{}, comparator interface{}) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{2, 4, 6} + slice1 := []int{1, 2, 3} + slice2 := []int{2, 4, 6} - isDouble := func(a, b int) bool { - return b == a*2 - } + isDouble := func(a, b int) bool { + return b == a*2 + } - res := slice.EqualWith(slice1, slice2, isDouble) + res := slice.EqualWith(slice1, slice2, isDouble) - fmt.Println(res) //true + fmt.Println(res) //true } ``` - - ### Every +Return true if all of the values in the slice pass the predicate function. The function signature should be func(index int, value interface{}) bool.
Signature: @@ -439,29 +439,28 @@ func main() { ```go func Every(slice, function interface{}) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res := slice.Every(nums, isEven) - fmt.Println(res) //false + res := slice.Every(nums, isEven) + fmt.Println(res) //false } ``` - - - ### Filter +Return all elements which match the function. Function signature should be func(index int, value interface{}) bool.
Signature: @@ -469,28 +468,28 @@ func main() { ```go func Filter(slice, function interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res := slice.Filter(nums, isEven) - fmt.Println(res) //[]int{2, 4} + res := slice.Filter(nums, isEven) + fmt.Println(res) //[]int{2, 4} } ``` - - ### Find +Iterates over elements of slice, returning the first one that passes a truth test on function.function signature should be func(index int, value interface{}) bool.
Signature: @@ -498,30 +497,29 @@ func main() { ```go func Find(slice, function interface{}) (interface{}, bool) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res, ok := slice.Find(nums, even) - fmt.Println(res) //2 - fmt.Println(ok) //true + res, ok := slice.Find(nums, even) + fmt.Println(res) //2 + fmt.Println(ok) //true } ``` - - - ### FindLast +iterates over elements of slice from end to begin, returning the last one that passes a truth test on function. The function signature should be func(index int, value interface{}) bool.
Signature: @@ -529,29 +527,29 @@ func main() { ```go func FindLast(slice, function interface{}) (interface{}, bool) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res, ok := slice.FindLast(nums, even) - fmt.Println(res) //4 - fmt.Println(ok) //true + res, ok := slice.FindLast(nums, even) + fmt.Println(res) //4 + fmt.Println(ok) //true } ``` - - ### FlattenDeep +flattens slice recursive.
Signature: @@ -559,24 +557,24 @@ func main() { ```go func FlattenDeep(slice interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} - res := slice.FlattenDeep(arr) - fmt.Println(res) //[]string{"a", "b", "c", "d"} + arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + res := slice.FlattenDeep(arr) + fmt.Println(res) //[]string{"a", "b", "c", "d"} } ``` - - ### ForEach +Iterates over elements of slice and invokes function for each element, function signature should be func(index int, value interface{}).
Signature: @@ -584,28 +582,27 @@ func main() { ```go func ForEach(slice, function interface{}) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - numbers := []int{1, 2, 3, 4, 5} - var numbersAddTwo []int - slice.ForEach(numbers, func(index int, value int) { - numbersAddTwo = append(numbersAddTwo, value+2) - }) - fmt.Println(numbersAddTwo) //[]int{3, 4, 5, 6, 7} + numbers := []int{1, 2, 3, 4, 5} + var numbersAddTwo []int + slice.ForEach(numbers, func(index int, value int) { + numbersAddTwo = append(numbersAddTwo, value+2) + }) + fmt.Println(numbersAddTwo) //[]int{3, 4, 5, 6, 7} } ``` - - - ### GroupBy +Iterates over elements of the slice, each element will be group by criteria, returns two slices. The function signature should be func(index int, value interface{}) bool.
Signature: @@ -613,30 +610,29 @@ func main() { ```go func GroupBy(slice, function interface{}) (interface{}, interface{}) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(i, num int) bool { - return (num % 2) == 0 - } - even, odd := slice.GroupBy(nums, evenFunc) + nums := []int{1, 2, 3, 4, 5, 6} + evenFunc := func(i, num int) bool { + return (num % 2) == 0 + } + even, odd := slice.GroupBy(nums, evenFunc) - fmt.Println(even) //[]int{2, 4, 6} - fmt.Println(odd) //]int{1, 3, 5} + fmt.Println(even) //[]int{2, 4, 6} + fmt.Println(odd) //]int{1, 3, 5} } ``` - - - ### IntSlice +Convert interface slice to int slice.
Signature: @@ -644,25 +640,24 @@ func main() { ```go func IntSlice(slice interface{}) []int ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - var nums = []interface{}{1, 2, 3} - res := slice.IntSlice(nums) - fmt.Println(res) //[]int{1, 2, 3} + var nums = []interface{}{1, 2, 3} + res := slice.IntSlice(nums) + fmt.Println(res) //[]int{1, 2, 3} } ``` - - - ### InterfaceSlice +Convert value to interface slice.
Signature: @@ -670,25 +665,24 @@ func main() { ```go func InterfaceSlice(slice interface{}) []interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - var nums = []int{}{1, 2, 3} - res := slice.InterfaceSlice(nums) - fmt.Println(res) //[]interface{}{1, 2, 3} + var nums = []int{}{1, 2, 3} + res := slice.InterfaceSlice(nums) + fmt.Println(res) //[]interface{}{1, 2, 3} } ``` - - - ### Intersection +Creates a slice of unique values that included by all slices.
Signature: @@ -696,26 +690,26 @@ func main() { ```go func Intersection(slices ...interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 2, 2, 3} - s2 := []int{1, 2, 3, 4} - res := slice.Intersection(s1, s2), + s1 := []int{1, 2, 2, 3} + s2 := []int{1, 2, 3, 4} + res := slice.Intersection(s1, s2), - fmt.Println(res) //[]int{1, 2, 3} + fmt.Println(res) //[]int{1, 2, 3} } ``` - - ### IndexOf +Returns the index at which the first occurrence of a value is found in a slice or return -1 if the value cannot be found.
Signature: @@ -723,27 +717,27 @@ func main() { ```go func IndexOf(slice, value interface{}) int ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.IndexOf(arr, "a") - fmt.Println(res1) //0 + arr := []string{"a", "a", "b", "c"} + res1 := slice.IndexOf(arr, "a") + fmt.Println(res1) //0 - res2 := slice.IndexOf(arr, "d") - fmt.Println(res2) //-1 + res2 := slice.IndexOf(arr, "d") + fmt.Println(res2) //-1 } ``` - - ### LastIndexOf +Returns the index at which the last occurrence of a value is found in a slice or return -1 if the value cannot be found.
Signature: @@ -751,26 +745,27 @@ func main() { ```go func LastIndexOf(slice, value interface{}) int ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.LastIndexOf(arr, "a") - fmt.Println(res1) //1 + arr := []string{"a", "a", "b", "c"} + res1 := slice.LastIndexOf(arr, "a") + fmt.Println(res1) //1 - res2 := slice.LastIndexOf(arr, "d") - fmt.Println(res2) //-1 + res2 := slice.LastIndexOf(arr, "d") + fmt.Println(res2) //-1 } ``` - ### InsertByIndex +insert the element into slice at index.
Signature: @@ -778,29 +773,28 @@ func main() { ```go func InsertByIndex(slice interface{}, index int, value interface{}) (interface{}, error) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s := []string{"a", "b", "c"} - - res1, _ := slice.InsertByIndex(s, 0, "1") - fmt.Println(res1) //[]string{"1", "a", "b", "c"} + s := []string{"a", "b", "c"} - res2, _ := slice.InsertByIndex(s, 3, []string{"1", "2", "3"}) - fmt.Println(res2) //[]string{"a", "b", "c", "1", "2", "3"} + res1, _ := slice.InsertByIndex(s, 0, "1") + fmt.Println(res1) //[]string{"1", "a", "b", "c"} + + res2, _ := slice.InsertByIndex(s, 3, []string{"1", "2", "3"}) + fmt.Println(res2) //[]string{"a", "b", "c", "1", "2", "3"} } ``` - - - ### Map +Creates an slice of values by running each element in slice thru function, function signature should be func(index int, value interface{}) interface{}.
Signature: @@ -808,28 +802,27 @@ func main() { ```go func Map(slice, function interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4} - multiplyTwo := func(i, num int) int { - return num * 2 - } - res := slice.Map(nums, multiplyTwo) - fmt.Println(res) //[]int{2, 4, 6, 8} + nums := []int{1, 2, 3, 4} + multiplyTwo := func(i, num int) int { + return num * 2 + } + res := slice.Map(nums, multiplyTwo) + fmt.Println(res) //[]int{2, 4, 6, 8} } ``` - - - ### ReverseSlice +Reverse the elements order in slice.
Signature: @@ -837,24 +830,24 @@ func main() { ```go func ReverseSlice(slice interface{}) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4} - slice.ReverseSlice(nums) - fmt.Println(res) //[]int{4, 3, 2, 1} + nums := []int{1, 2, 3, 4} + slice.ReverseSlice(nums) + fmt.Println(res) //[]int{4, 3, 2, 1} } ``` - - ### Reduce +Reduce slice, function signature should be func(index int, value1, value2 interface{}) interface{}.
Signature: @@ -862,28 +855,27 @@ func main() { ```go func Reduce(slice, function, zero interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4} - reduceFunc := func(i, v1, v2 int) int { - return v1 + v2 - } - res := slice.Reduce(nums, reduceFunc, 0) - fmt.Println(res) //10 + nums := []int{1, 2, 3, 4} + reduceFunc := func(i, v1, v2 int) int { + return v1 + v2 + } + res := slice.Reduce(nums, reduceFunc, 0) + fmt.Println(res) //10 } ``` - - - ### Shuffle +Creates an slice of shuffled values.
Signature: @@ -891,24 +883,24 @@ func main() { ```go func Shuffle(slice interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5} - res := slice.Shuffle(nums) - fmt.Println(res) //3,1,5,4,2 + nums := []int{1, 2, 3, 4, 5} + res := slice.Shuffle(nums) + fmt.Println(res) //3,1,5,4,2 } ``` - - ### SortByField +Sort struct slice by field. Slice element should be struct, field type should be int, uint, string, or bool. Default sort type is ascending (asc), if descending order, set sortType to desc
Signature: @@ -916,42 +908,42 @@ func main() { ```go func SortByField(slice interface{}, field string, sortType ...string) error ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - type student struct { - name string - age int - } - students := []student{ - {"a", 10}, - {"b", 15}, - {"c", 5}, - {"d", 6}, - } - err := slice.SortByField(students, "age", "desc") - if err != nil { - fmt.Println(err) - } - fmt.Println(students) - // []students{ - // {"b", 15}, - // {"a", 10}, - // {"d", 6}, - // {"c", 5}, - // } + type student struct { + name string + age int + } + students := []student{ + {"a", 10}, + {"b", 15}, + {"c", 5}, + {"d", 6}, + } + err := slice.SortByField(students, "age", "desc") + if err != nil { + fmt.Println(err) + } + fmt.Println(students) + // []students{ + // {"b", 15}, + // {"a", 10}, + // {"d", 6}, + // {"c", 5}, + // } } ``` - - ### Some +Return true if any of the values in the list pass the predicate function, function signature should be func(index int, value interface{}) bool.
Signature: @@ -959,28 +951,28 @@ func main() { ```go func Some(slice, function interface{}) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res := slice.Some(nums, isEven) - fmt.Println(res) //true + res := slice.Some(nums, isEven) + fmt.Println(res) //true } ``` - - ### StringSlice +Convert interface slice to string slice.
Signature: @@ -988,24 +980,24 @@ func main() { ```go func StringSlice(slice interface{}) []string ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - var s = []interface{}{"a", "b", "c"} - res := slice.StringSlice(s) - fmt.Println(res) //[]string{"a", "b", "c"} + var s = []interface{}{"a", "b", "c"} + res := slice.StringSlice(s) + fmt.Println(res) //[]string{"a", "b", "c"} } ``` - - ### ToSlice +Returns a slices of a variable parameter transformation
Signature: @@ -1013,23 +1005,23 @@ func main() { ```go func ToSlice(value ...interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.ToSlice("a", "b") - fmt.Println(res) //{"a", "b"} + res := slice.ToSlice("a", "b") + fmt.Println(res) //{"a", "b"} } ``` - - ### ToSlicePointer +Returns a pointer to the slices of a variable parameter transformation
Signature: @@ -1037,25 +1029,25 @@ func main() { ```go func ToSlicePointer(value ...interface{}) []*interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - str1 := "a" - str2 := "b" - res := slice.ToSlicePointer(str1, str2) - fmt.Println(res) // res -> []*string{&str1, &str2} + str1 := "a" + str2 := "b" + res := slice.ToSlicePointer(str1, str2) + fmt.Println(res) // res -> []*string{&str1, &str2} } ``` - - ### Unique +Remove duplicate elements in slice.
Signature: @@ -1063,23 +1055,23 @@ func main() { ```go func Unique(slice interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Unique([]int{1, 2, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + res := slice.Unique([]int{1, 2, 2, 3}) + fmt.Println(res) //[]int{1, 2, 3} } ``` - - ### UniqueBy +Call iteratee func with every item of slice, then remove duplicated.
Signature: @@ -1087,25 +1079,25 @@ func main() { ```go func UniqueBy(slice, iteratee interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int { - return val % 4 - }) - fmt.Println(res) //[]int{1, 2, 3, 0} + res := slice.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int { + return val % 4 + }) + fmt.Println(res) //[]int{1, 2, 3, 0} } ``` - - ### Union +Creates a slice of unique values, in order, from all given slices. using == for equality comparisons.
Signature: @@ -1113,26 +1105,26 @@ func main() { ```go func Union(slices ...interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 3, 4, 6} - s2 := []int{1, 2, 5, 6} - res := slice.Union(s1, s2) + s1 := []int{1, 3, 4, 6} + s2 := []int{1, 2, 5, 6} + res := slice.Union(s1, s2) - fmt.Println(res) //[]int{1, 3, 4, 6, 2, 5} + fmt.Println(res) //[]int{1, 3, 4, 6, 2, 5} } ``` - - ### UpdateByIndex +Update the slice element at index. if param index < 0 or index >= len(slice), will return error.
Signature: @@ -1140,26 +1132,25 @@ func main() { ```go func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s := []string{"a", "b", "c"} - - res1, _ := slice.UpdateByIndex(s, 0, "1") - fmt.Println(res1) //[]string{"1", "b", "c"} + s := []string{"a", "b", "c"} + + res1, _ := slice.UpdateByIndex(s, 0, "1") + fmt.Println(res1) //[]string{"1", "b", "c"} } ``` - - - ### Without +Creates a slice excluding all given values.
Signature: @@ -1167,27 +1158,17 @@ func main() { ```go func Without(slice interface{}, values ...interface{}) interface{} ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Without([]int{1, 2, 3, 4, 5}, 1, 2) - fmt.Println(res) //[]int{3, 4, 5} + res := slice.Without([]int{1, 2, 3, 4, 5}, 1, 2) + fmt.Println(res) //[]int{3, 4, 5} } ``` - - - - - - - - - - - diff --git a/docs/slice_zh-CN.md b/docs/slice_zh-CN.md index 7105135..8e6e24e 100644 --- a/docs/slice_zh-CN.md +++ b/docs/slice_zh-CN.md @@ -1,5 +1,6 @@ # Slice -slice包包含操作切片的方法集合。 + +slice 包包含操作切片的方法集合。 @@ -7,10 +8,10 @@ slice包包含操作切片的方法集合。 [https://github.com/duke-git/lancet/blob/v1/slice/slice.go](https://github.com/duke-git/lancet/blob/v1/slice/slice.go) - ## 用法: + ```go import ( "github.com/duke-git/lancet/slice" @@ -20,52 +21,54 @@ import ( ## 目录 -- [AppendIfAbsent](#AppendIfAbsent) -- [Contain](#Contain) -- [ContainSubSlice](#ContainSubSlice) -- [Chunk](#Chunk) -- [Compact](#Compact) -- [Concat](#Concat) -- [Count](#Count) -- [Difference](#Difference) -- [DifferenceBy](#DifferenceBy) -- [DeleteByIndex](#DeleteByIndex) -- [Drop](#Drop) -- [Equal](#Equal) -- [EqualWith](#EqualWith) -- [Every](#Every) -- [Filter](#Filter) -- [Find](#Find) -- [FindLast](#FindLast) -- [FlattenDeep](#FlattenDeep) -- [ForEach](#ForEach) -- [GroupBy](#GroupBy) -- [IntSlice](#IntSlice) -- [InterfaceSlice](#InterfaceSlice) -- [Intersection](#Intersection) -- [InsertByIndex](#InsertByIndex) -- [IndexOf](#IndexOf) -- [LastIndexOf](#LastIndexOf) -- [Map](#Map) -- [ReverseSlice](#ReverseSlice) -- [Reduce](#Reduce) -- [Shuffle](#Shuffle) -- [SortByField](#SortByField) -- [Some](#Some) -- [StringSlice](#StringSlice) -- [ToSlice](#ToSlice) -- [ToSlicePointer](#ToSlicePointer) -- [Unique](#Unique) -- [UniqueBy](#UniqueBy) -- [Union](#Union) -- [UpdateByIndex](#UpdateByIndex) -- [Without](#Without) + +- [AppendIfAbsent](#AppendIfAbsent) +- [Contain](#Contain) +- [ContainSubSlice](#ContainSubSlice) +- [Chunk](#Chunk) +- [Compact](#Compact) +- [Concat](#Concat) +- [Count](#Count) +- [Difference](#Difference) +- [DifferenceBy](#DifferenceBy) +- [DeleteByIndex](#DeleteByIndex) +- [Drop](#Drop) +- [Equal](#Equal) +- [EqualWith](#EqualWith) +- [Every](#Every) +- [Filter](#Filter) +- [Find](#Find) +- [FindLast](#FindLast) +- [FlattenDeep](#FlattenDeep) +- [ForEach](#ForEach) +- [GroupBy](#GroupBy) +- [IntSlice](#IntSlice) +- [InterfaceSlice](#InterfaceSlice) +- [Intersection](#Intersection) +- [InsertByIndex](#InsertByIndex) +- [IndexOf](#IndexOf) +- [LastIndexOf](#LastIndexOf) +- [Map](#Map) +- [ReverseSlice](#ReverseSlice) +- [Reduce](#Reduce) +- [Shuffle](#Shuffle) +- [SortByField](#SortByField) +- [Some](#Some) +- [StringSlice](#StringSlice) +- [ToSlice](#ToSlice) +- [ToSlicePointer](#ToSlicePointer) +- [Unique](#Unique) +- [UniqueBy](#UniqueBy) +- [Union](#Union) +- [UpdateByIndex](#UpdateByIndex) +- [Without](#Without) ## 文档 ### AppendIfAbsent +当前切片中不包含值时,将该值追加到切片中
函数签名: @@ -73,27 +76,27 @@ import ( ```go func AppendIfAbsent(slice interface{}, value interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - strs := []string{"a", "b"} - res1 := slice.AppendIfAbsent(strs, "a") - fmt.Println(res1) //[]string{"a", "b"} + strs := []string{"a", "b"} + res1 := slice.AppendIfAbsent(strs, "a") + fmt.Println(res1) //[]string{"a", "b"} - res2 := slice.AppendIfAbsent(strs, "cannot") - fmt.Println(res2"} + res2 := slice.AppendIfAbsent(strs, "cannot") + fmt.Println(res2"} } ``` - - ### Contain +判断slice是否包含value
函数签名: @@ -101,22 +104,23 @@ func main() { ```go func Contain(iterableType interface{}, value interface{}) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Contain([]string{"a", "b", "c"}, "a") - fmt.Println(res) //true + res := slice.Contain([]string{"a", "b", "c"}, "a") + fmt.Println(res) //true } ``` - ### ContainSubSlice +判断slice是否包含subslice
函数签名: @@ -124,24 +128,23 @@ func main() { ```go func ContainSubSlice(slice interface{}, subslice interface{}) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) - fmt.Println(res) //true + res := slice.ContainSubSlice([]string{"a", "b", "c"}, []string{"a", "b"}) + fmt.Println(res) //true } ``` - - - ### Chunk +按照size参数均分slice
函数签名: @@ -149,24 +152,24 @@ func main() { ```go func Chunk(slice []interface{}, size int) [][]interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := []string{"a", "b", "c", "d", "e"} - res := slice.Chunk(InterfaceSlice(arr), 3) - fmt.Println(res) //[][]interface{}{{"a", "b", "c"}, {"d", "e"}} + arr := []string{"a", "b", "c", "d", "e"} + res := slice.Chunk(InterfaceSlice(arr), 3) + fmt.Println(res) //[][]interface{}{{"a", "b", "c"}, {"d", "e"}} } ``` - - ### Compact +去除slice中的假值(false values are false, nil, 0, "")
函数签名: @@ -174,22 +177,23 @@ func main() { ```go func Compact(slice interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Compact([]int{0, 1, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + res := slice.Compact([]int{0, 1, 2, 3}) + fmt.Println(res) //[]int{1, 2, 3} } ``` - ### Concat +连接values到slice中,values类型可以是切片或多个值
函数签名: @@ -197,26 +201,26 @@ func main() { ```go func Concat(slice interface{}, values ...interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res1 := slice.Concat([]int{1, 2, 3}, 4, 5) - fmt.Println(res1) //[]int{1, 2, 3, 4, 5} + res1 := slice.Concat([]int{1, 2, 3}, 4, 5) + fmt.Println(res1) //[]int{1, 2, 3, 4, 5} - res2 := slice.Concat([]int{1, 2, 3}, []int{4, 5}) - fmt.Println(res2) //[]int{1, 2, 3, 4, 5} + res2 := slice.Concat([]int{1, 2, 3}, []int{4, 5}) + fmt.Println(res2) //[]int{1, 2, 3, 4, 5} } ``` - - ### Count +遍历切片,对每个元素执行函数function. 返回符合函数返回值为true的元素的个数,函数签名必须是func(index int, value interface{}) bool
函数签名: @@ -224,29 +228,28 @@ func main() { ```go func Count(slice, function interface{}) int ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(i, num int) bool { - return (num % 2) == 0 - } + nums := []int{1, 2, 3, 4, 5, 6} + evenFunc := func(i, num int) bool { + return (num % 2) == 0 + } - res := slice.Count(nums, evenFunc) - fmt.Println(res) //3 + res := slice.Count(nums, evenFunc) + fmt.Println(res) //3 } ``` - - - ### Difference +创建一个切片,其元素不包含在另一个给定切片中
函数签名: @@ -254,27 +257,26 @@ func main() { ```go func Difference(slice1, slice2 interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6} - res := slice.Difference(s1, s2) - fmt.Println(res) //[]int{1, 2, 3} + res := slice.Difference(s1, s2) + fmt.Println(res) //[]int{1, 2, 3} } ``` - - - ### DifferenceBy +在slice和comparedSlice中的每个元素调用iteratee函数,并比较它们的返回值,如果不想等返回在slice中对应的值
函数签名: @@ -282,30 +284,29 @@ func main() { ```go func DifferenceBy(slice interface{}, comparedSlice interface{}, iterateeFn interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 2, 3, 4, 5} - s2 := []int{4, 5, 6} - addOne := func(i int, v int) int { - return v + 1 - } + s1 := []int{1, 2, 3, 4, 5} + s2 := []int{4, 5, 6} + addOne := func(i int, v int) int { + return v + 1 + } - res := slice.DifferenceBy(s1, s2, addOne) - fmt.Println(res) //[]int{1, 2} + res := slice.DifferenceBy(s1, s2, addOne) + fmt.Println(res) //[]int{1, 2} } ``` - - - ### DeleteByIndex +删除切片中从开始索引到结束索引-1的元素
函数签名: @@ -313,28 +314,27 @@ func main() { ```go func DeleteByIndex(slice interface{}, start int, end ...int) (interface{}, error) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res1 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 3) - fmt.Println(res1) //[]string{"a", "b", "c", "e"} + res1 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 3) + fmt.Println(res1) //[]string{"a", "b", "c", "e"} - res2 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 0, 2) - fmt.Println(res2) //[]string{"c", "d", "e"} + res2 := slice.DeleteByIndex([]string{"a", "b", "c", "d", "e"}, 0, 2) + fmt.Println(res2) //[]string{"c", "d", "e"} } ``` - - - ### Drop +创建一个切片,当 n > 0 时从开头删除 n 个元素,或者当 n < 0 时从结尾删除 n 个元素
函数签名: @@ -342,29 +342,29 @@ func main() { ```go func Drop(slice interface{}, n int) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res1 := slice.Drop([]int{}, 0) - fmt.Println(res1) //[]int{} + res1 := slice.Drop([]int{}, 0) + fmt.Println(res1) //[]int{} - res2 := slice.Drop([]int{1, 2, 3, 4, 5}, 1) - fmt.Println(res2) //[]int{2, 3, 4, 5} + res2 := slice.Drop([]int{1, 2, 3, 4, 5}, 1) + fmt.Println(res2) //[]int{2, 3, 4, 5} - res3 := slice.Drop([]int{1, 2, 3, 4, 5}, -1) - fmt.Println(res3) //[]int{1, 2, 3, 4} + res3 := slice.Drop([]int{1, 2, 3, 4, 5}, -1) + fmt.Println(res3) //[]int{1, 2, 3, 4} } ``` - - ### Equal +检查两个切片是否相等,相等条件:切片长度相同,元素顺序和值都相同
函数签名: @@ -372,30 +372,30 @@ func main() { ```go func Equal(slice1, slice2 interface{}) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{1, 2, 3} - slice3 := []int{3, 2, 1} + slice1 := []int{1, 2, 3} + slice2 := []int{1, 2, 3} + slice3 := []int{3, 2, 1} - res1 := slice.Equal(slice1, slice2) - res2 := slice.Equal(slice1, slice3) + res1 := slice.Equal(slice1, slice2) + res2 := slice.Equal(slice1, slice3) - fmt.Println(res1) //true - fmt.Println(res2) //false + fmt.Println(res1) //true + fmt.Println(res2) //false } ``` - - ### EqualWith +检查两个切片是否相等,相等条件:对两个切片的元素调用比较函数comparator,返回true。 comparator函数签名: func(a interface{}, b interface{}) bool
函数签名: @@ -403,31 +403,31 @@ func main() { ```go func EqualWith(slice1, slice2 interface{}, comparator interface{}) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - slice1 := []int{1, 2, 3} - slice2 := []int{2, 4, 6} + slice1 := []int{1, 2, 3} + slice2 := []int{2, 4, 6} - isDouble := func(a, b int) bool { - return b == a*2 - } + isDouble := func(a, b int) bool { + return b == a*2 + } - res := slice.EqualWith(slice1, slice2, isDouble) + res := slice.EqualWith(slice1, slice2, isDouble) - fmt.Println(res) //true + fmt.Println(res) //true } ``` - - ### Every +如果切片中的所有值都通过谓词函数,则返回true。 函数签名应该是func(index int, value interface{}) bool
函数签名: @@ -435,29 +435,28 @@ func main() { ```go func Every(slice, function interface{}) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res := slice.Every(nums, isEven) - fmt.Println(res) //false + res := slice.Every(nums, isEven) + fmt.Println(res) //false } ``` - - - ### Filter +返回与函数匹配的所有元素。 函数签名应该是 func(index int, value interface{}) bool
函数签名: @@ -465,28 +464,28 @@ func main() { ```go func Filter(slice, function interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res := slice.Filter(nums, isEven) - fmt.Println(res) //[]int{2, 4} + res := slice.Filter(nums, isEven) + fmt.Println(res) //[]int{2, 4} } ``` - - ### Find +遍历slice的元素,返回第一个通过function真值测试的元素。函数签名应该是 func(index int, value interface{}) bool
函数签名: @@ -494,30 +493,29 @@ func main() { ```go func Find(slice, function interface{}) (interface{}, bool) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res, ok := slice.Find(nums, even) - fmt.Println(res) //2 - fmt.Println(ok) //true + res, ok := slice.Find(nums, even) + fmt.Println(res) //2 + fmt.Println(ok) //true } ``` - - - ### FindLast +从头到尾遍历 slice 的元素,返回最后一个通过函数真值测试的元素。 函数签名应该是 func(index int, value interface{}) bool。
函数签名: @@ -525,29 +523,29 @@ func main() { ```go func FindLast(slice, function interface{}) (interface{}, bool) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res, ok := slice.FindLast(nums, even) - fmt.Println(res) //4 - fmt.Println(ok) //true + res, ok := slice.FindLast(nums, even) + fmt.Println(res) //4 + fmt.Println(ok) //true } ``` - - ### FlattenDeep +flattens slice recursive.
函数签名: @@ -555,26 +553,24 @@ func main() { ```go func FlattenDeep(slice interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} - res := slice.FlattenDeep(arr) - fmt.Println(res) //[]string{"a", "b", "c", "d"} + arr := [][][]string{{{"a", "b"}}, {{"c", "d"}}} + res := slice.FlattenDeep(arr) + fmt.Println(res) //[]string{"a", "b", "c", "d"} } ``` - - - - ### ForEach +遍历slice的元素并为每个元素调用函数,函数签名应该是func(index int, value interface{})
函数签名: @@ -582,28 +578,27 @@ func main() { ```go func ForEach(slice, function interface{}) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - numbers := []int{1, 2, 3, 4, 5} - var numbersAddTwo []int - slice.ForEach(numbers, func(index int, value int) { - numbersAddTwo = append(numbersAddTwo, value+2) - }) - fmt.Println(numbersAddTwo) //[]int{3, 4, 5, 6, 7} + numbers := []int{1, 2, 3, 4, 5} + var numbersAddTwo []int + slice.ForEach(numbers, func(index int, value int) { + numbersAddTwo = append(numbersAddTwo, value+2) + }) + fmt.Println(numbersAddTwo) //[]int{3, 4, 5, 6, 7} } ``` - - - ### GroupBy +迭代切片的元素,每个元素将按条件分组,返回两个切片。 函数签名应该是func(index int, value interface{}) bool
函数签名: @@ -611,30 +606,29 @@ func main() { ```go func GroupBy(slice, function interface{}) (interface{}, interface{}) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5, 6} - evenFunc := func(i, num int) bool { - return (num % 2) == 0 - } - even, odd := slice.GroupBy(nums, evenFunc) + nums := []int{1, 2, 3, 4, 5, 6} + evenFunc := func(i, num int) bool { + return (num % 2) == 0 + } + even, odd := slice.GroupBy(nums, evenFunc) - fmt.Println(even) //[]int{2, 4, 6} - fmt.Println(odd) //]int{1, 3, 5} + fmt.Println(even) //[]int{2, 4, 6} + fmt.Println(odd) //]int{1, 3, 5} } ``` - - - ### IntSlice +将接口切片转换为int切片
函数签名: @@ -642,25 +636,24 @@ func main() { ```go func IntSlice(slice interface{}) []int ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - var nums = []interface{}{1, 2, 3} - res := slice.IntSlice(nums) - fmt.Println(res) //[]int{1, 2, 3} + var nums = []interface{}{1, 2, 3} + res := slice.IntSlice(nums) + fmt.Println(res) //[]int{1, 2, 3} } ``` - - - ### InterfaceSlice +将值转换为接口切片
函数签名: @@ -668,25 +661,24 @@ func main() { ```go func InterfaceSlice(slice interface{}) []interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - var nums = []int{}{1, 2, 3} - res := slice.InterfaceSlice(nums) - fmt.Println(res) //[]interface{}{1, 2, 3} + var nums = []int{}{1, 2, 3} + res := slice.InterfaceSlice(nums) + fmt.Println(res) //[]interface{}{1, 2, 3} } ``` - - - ### Intersection +多个切片的交集
函数签名: @@ -694,26 +686,26 @@ func main() { ```go func Intersection(slices ...interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 2, 2, 3} - s2 := []int{1, 2, 3, 4} - res := slice.Intersection(s1, s2), + s1 := []int{1, 2, 2, 3} + s2 := []int{1, 2, 3, 4} + res := slice.Intersection(s1, s2), - fmt.Println(res) //[]int{1, 2, 3} + fmt.Println(res) //[]int{1, 2, 3} } ``` - - ### IndexOf +返回在切片中找到值的第一个匹配项的索引,如果找不到值,则返回-1
函数签名: @@ -721,27 +713,27 @@ func main() { ```go func IndexOf(slice, value interface{}) int ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.IndexOf(arr, "a") - fmt.Println(res1) //0 + arr := []string{"a", "a", "b", "c"} + res1 := slice.IndexOf(arr, "a") + fmt.Println(res1) //0 - res2 := slice.IndexOf(arr, "d") - fmt.Println(res2) //-1 + res2 := slice.IndexOf(arr, "d") + fmt.Println(res2) //-1 } ``` - - ### LastIndexOf +返回在切片中找到最后一个值的索引,如果找不到该值,则返回-1
函数签名: @@ -749,27 +741,27 @@ func main() { ```go func LastIndexOf(slice, value interface{}) int ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - arr := []string{"a", "a", "b", "c"} - res1 := slice.LastIndexOf(arr, "a") - fmt.Println(res1) //1 + arr := []string{"a", "a", "b", "c"} + res1 := slice.LastIndexOf(arr, "a") + fmt.Println(res1) //1 - res2 := slice.LastIndexOf(arr, "d") - fmt.Println(res2) //-1 + res2 := slice.LastIndexOf(arr, "d") + fmt.Println(res2) //-1 } ``` - - ### InsertByIndex +将元素插入到索引处的切片中
函数签名: @@ -777,29 +769,28 @@ func main() { ```go func InsertByIndex(slice interface{}, index int, value interface{}) (interface{}, error) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s := []string{"a", "b", "c"} - - res1, _ := slice.InsertByIndex(s, 0, "1") - fmt.Println(res1) //[]string{"1", "a", "b", "c"} + s := []string{"a", "b", "c"} - res2, _ := slice.InsertByIndex(s, 3, []string{"1", "2", "3"}) - fmt.Println(res2) //[]string{"a", "b", "c", "1", "2", "3"} + res1, _ := slice.InsertByIndex(s, 0, "1") + fmt.Println(res1) //[]string{"1", "a", "b", "c"} + + res2, _ := slice.InsertByIndex(s, 3, []string{"1", "2", "3"}) + fmt.Println(res2) //[]string{"a", "b", "c", "1", "2", "3"} } ``` - - - ### Map +通过运行函数slice中的每个元素来创建一个值切片,函数签名应该是func(index int, value interface{}) interface{}。
函数签名: @@ -807,28 +798,27 @@ func main() { ```go func Map(slice, function interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4} - multiplyTwo := func(i, num int) int { - return num * 2 - } - res := slice.Map(nums, multiplyTwo) - fmt.Println(res) //[]int{2, 4, 6, 8} + nums := []int{1, 2, 3, 4} + multiplyTwo := func(i, num int) int { + return num * 2 + } + res := slice.Map(nums, multiplyTwo) + fmt.Println(res) //[]int{2, 4, 6, 8} } ``` - - - ### ReverseSlice +反转切片中的元素顺序
函数签名: @@ -836,24 +826,24 @@ func main() { ```go func ReverseSlice(slice interface{}) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4} - slice.ReverseSlice(nums) - fmt.Println(res) //[]int{4, 3, 2, 1} + nums := []int{1, 2, 3, 4} + slice.ReverseSlice(nums) + fmt.Println(res) //[]int{4, 3, 2, 1} } ``` - - ### Reduce +将slice中的元素运行函数,返回运行结果。函数签名应该是func(index int, value1, value2 interface{}) interface{}。
函数签名: @@ -861,28 +851,27 @@ func main() { ```go func Reduce(slice, function, zero interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4} - reduceFunc := func(i, v1, v2 int) int { - return v1 + v2 - } - res := slice.Reduce(nums, reduceFunc, 0) - fmt.Println(res) //10 + nums := []int{1, 2, 3, 4} + reduceFunc := func(i, v1, v2 int) int { + return v1 + v2 + } + res := slice.Reduce(nums, reduceFunc, 0) + fmt.Println(res) //10 } ``` - - - ### Shuffle +随机打乱切片中的元素顺序
函数签名: @@ -890,24 +879,24 @@ func main() { ```go func Shuffle(slice interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 4, 5} - res := slice.Shuffle(nums) - fmt.Println(res) //3,1,5,4,2 + nums := []int{1, 2, 3, 4, 5} + res := slice.Shuffle(nums) + fmt.Println(res) //3,1,5,4,2 } ``` - - ### SortByField +按字段对结构切片进行排序。slice元素应为struct,字段类型应为int、uint、string或bool。 默认排序类型是升序(asc),如果是降序,设置 sortType 为 desc
函数签名: @@ -915,42 +904,42 @@ func main() { ```go func SortByField(slice interface{}, field string, sortType ...string) error ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - type student struct { - name string - age int - } - students := []student{ - {"a", 10}, - {"b", 15}, - {"c", 5}, - {"d", 6}, - } - err := slice.SortByField(students, "age", "desc") - if err != nil { - fmt.Println(err) - } - fmt.Println(students) - // []students{ - // {"b", 15}, - // {"a", 10}, - // {"d", 6}, - // {"c", 5}, - // } + type student struct { + name string + age int + } + students := []student{ + {"a", 10}, + {"b", 15}, + {"c", 5}, + {"d", 6}, + } + err := slice.SortByField(students, "age", "desc") + if err != nil { + fmt.Println(err) + } + fmt.Println(students) + // []students{ + // {"b", 15}, + // {"a", 10}, + // {"d", 6}, + // {"c", 5}, + // } } ``` - - ### Some +如果列表中的任何值通过谓词函数,则返回true,函数签名应该是func(index int, value interface{}) bool .
函数签名: @@ -958,28 +947,28 @@ func main() { ```go func Some(slice, function interface{}) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - nums := []int{1, 2, 3, 5} - isEven := func(i, num int) bool { - return num%2 == 0 - } + nums := []int{1, 2, 3, 5} + isEven := func(i, num int) bool { + return num%2 == 0 + } - res := slice.Some(nums, isEven) - fmt.Println(res) //true + res := slice.Some(nums, isEven) + fmt.Println(res) //true } ``` - - ### StringSlice +将接口切片转换为字符串切片
函数签名: @@ -987,24 +976,24 @@ func main() { ```go func StringSlice(slice interface{}) []string ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - var s = []interface{}{"a", "b", "c"} - res := slice.StringSlice(s) - fmt.Println(res) //[]string{"a", "b", "c"} + var s = []interface{}{"a", "b", "c"} + res := slice.StringSlice(s) + fmt.Println(res) //[]string{"a", "b", "c"} } ``` - - ### ToSlice +将可变参数转为切片
函数签名: @@ -1012,23 +1001,23 @@ func main() { ```go func ToSlice(value ...interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - res := slice.ToSlice("a", "b") - fmt.Println(res) //{"a", "b"} + res := slice.ToSlice("a", "b") + fmt.Println(res) //{"a", "b"} } ``` - - ### ToSlicePointer +将可变参数转为指针切片
函数签名: @@ -1036,25 +1025,25 @@ func main() { ```go func ToSlicePointer(value ...interface{}) []*interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/v2/slice" + "fmt" + "github.com/duke-git/lancet/v2/slice" ) func main() { - str1 := "a" - str2 := "b" - res := slice.ToSlicePointer(str1, str2) - fmt.Println(res) // res -> []*string{&str1, &str2} + str1 := "a" + str2 := "b" + res := slice.ToSlicePointer(str1, str2) + fmt.Println(res) // res -> []*string{&str1, &str2} } ``` - - ### Unique +删除切片中的重复元素
函数签名: @@ -1062,23 +1051,23 @@ func main() { ```go func Unique(slice interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Unique([]int{1, 2, 2, 3}) - fmt.Println(res) //[]int{1, 2, 3} + res := slice.Unique([]int{1, 2, 2, 3}) + fmt.Println(res) //[]int{1, 2, 3} } ``` - - ### UniqueBy +对切片的每个项目调用iteratee函数,然后删除重复的
函数签名: @@ -1086,24 +1075,25 @@ func main() { ```go func UniqueBy(slice, iteratee interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int { - return val % 4 - }) - fmt.Println(res) //[]int{1, 2, 3, 0} + res := slice.UniqueBy([]int{1, 2, 3, 4, 5, 6}, func(val int) int { + return val % 4 + }) + fmt.Println(res) //[]int{1, 2, 3, 0} } ``` - ### Union +从所有给定的切片按顺序创建一个唯一值切片。 使用 == 进行相等比较。
函数签名: @@ -1111,26 +1101,26 @@ func main() { ```go func Union(slices ...interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s1 := []int{1, 3, 4, 6} - s2 := []int{1, 2, 5, 6} - res := slice.Union(s1, s2) + s1 := []int{1, 3, 4, 6} + s2 := []int{1, 2, 5, 6} + res := slice.Union(s1, s2) - fmt.Println(res) //[]int{1, 3, 4, 6, 2, 5} + fmt.Println(res) //[]int{1, 3, 4, 6, 2, 5} } ``` - - ### UpdateByIndex +更新索引处的切片元素。 如果 param index < 0 或 index >= len(slice),将返回错误
函数签名: @@ -1138,26 +1128,25 @@ func main() { ```go func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error) ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - s := []string{"a", "b", "c"} - - res1, _ := slice.UpdateByIndex(s, 0, "1") - fmt.Println(res1) //[]string{"1", "b", "c"} + s := []string{"a", "b", "c"} + + res1, _ := slice.UpdateByIndex(s, 0, "1") + fmt.Println(res1) //[]string{"1", "b", "c"} } ``` - - - ### Without +创建一个不包括所有给定值的切片
函数签名: @@ -1165,27 +1154,17 @@ func main() { ```go func Without(slice interface{}, values ...interface{}) interface{} ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/slice" + "fmt" + "github.com/duke-git/lancet/slice" ) func main() { - res := slice.Without([]int{1, 2, 3, 4, 5}, 1, 2) - fmt.Println(res) //[]int{3, 4, 5} + res := slice.Without([]int{1, 2, 3, 4, 5}, 1, 2) + fmt.Println(res) //[]int{3, 4, 5} } ``` - - - - - - - - - - - diff --git a/docs/system.md b/docs/system.md index bf7edcb..1b8ade4 100644 --- a/docs/system.md +++ b/docs/system.md @@ -1,4 +1,5 @@ # System + Package system contains some functions about os, runtime, shell command. @@ -7,10 +8,10 @@ Package system contains some functions about os, runtime, shell command. [https://github.com/duke-git/lancet/blob/v1/system/os.go](https://github.com/duke-git/lancet/blob/v1/system/os.go) - ## Usage: + ```go import ( "github.com/duke-git/lancet/system" @@ -20,23 +21,23 @@ import ( ## Index -- [IsWindows](#IsWindows) -- [IsLinux](#IsLinux) -- [IsMac](#IsMac) -- [GetOsEnv](#GetOsEnv) -- [SetOsEnv](#SetOsEnv) -- [RemoveOsEnv](#RemoveOsEnv) -- [CompareOsEnv](#CompareOsEnv) -- [ExecCommand](#ExecCommand) -- [GetOsBits](#GetOsBits) - + +- [IsWindows](#IsWindows) +- [IsLinux](#IsLinux) +- [IsMac](#IsMac) +- [GetOsEnv](#GetOsEnv) +- [SetOsEnv](#SetOsEnv) +- [RemoveOsEnv](#RemoveOsEnv) +- [CompareOsEnv](#CompareOsEnv) +- [ExecCommand](#ExecCommand) +- [GetOsBits](#GetOsBits) ## Documentation - ### IsWindows +Check if current os is windows.
Signature: @@ -44,24 +45,23 @@ import ( ```go func IsWindows() bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - isOsWindows := system.IsWindows() - fmt.Println(isOsWindows) + isOsWindows := system.IsWindows() + fmt.Println(isOsWindows) } ``` - - - ### IsLinux +Check if current os is linux.
Signature: @@ -69,23 +69,23 @@ func main() { ```go func IsLinux() bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - isOsLinux := system.IsLinux() - fmt.Println(isOsLinux) + isOsLinux := system.IsLinux() + fmt.Println(isOsLinux) } ``` - - ### IsMac +Check if current os is macos.
Signature: @@ -93,23 +93,23 @@ func main() { ```go func IsMac() bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - isOsMac := system.IsMac - fmt.Println(isOsMac) + isOsMac := system.IsMac + fmt.Println(isOsMac) } ``` - - ### GetOsEnv +Gets the value of the environment variable named by the key.
Signature: @@ -117,23 +117,23 @@ func main() { ```go func GetOsEnv(key string) string ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - fooEnv := system.GetOsEnv("foo") - fmt.Println(fooEnv) + fooEnv := system.GetOsEnv("foo") + fmt.Println(fooEnv) } ``` - - ### SetOsEnv +Sets the value of the environment variable named by the key.
Signature: @@ -141,24 +141,23 @@ func main() { ```go func SetOsEnv(key, value string) error ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - err := system.SetOsEnv("foo", "foo_value") - fmt.Println(err) + err := system.SetOsEnv("foo", "foo_value") + fmt.Println(err) } ``` - - - ### RemoveOsEnv +Remove a single environment variable.
Signature: @@ -166,25 +165,25 @@ func main() { ```go func RemoveOsEnv(key string) error ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - err := system.RemoveOsEnv("foo") - if err != nil { - fmt.Println(err) - } + err := system.RemoveOsEnv("foo") + if err != nil { + fmt.Println(err) + } } ``` - - ### CompareOsEnv +Get env named by the key and compare it with comparedEnv.
Signature: @@ -192,25 +191,24 @@ func main() { ```go func CompareOsEnv(key, comparedEnv string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - system.SetOsEnv("foo", "foo_value") - res := system.CompareOsEnv("foo", "foo_value") - fmt.Println(res) //true + system.SetOsEnv("foo", "foo_value") + res := system.CompareOsEnv("foo", "foo_value") + fmt.Println(res) //true } ``` - - - ### CompareOsEnv +use shell /bin/bash -c(linux) or cmd (windows) to execute command.
Signature: @@ -218,25 +216,25 @@ func main() { ```go func ExecCommand(command string) (stdout, stderr string, err error) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - out, errout, err := system.ExecCommand("ls") - fmt.Println(out) - fmt.Println(errout) - fmt.Println(err) + out, errout, err := system.ExecCommand("ls") + fmt.Println(out) + fmt.Println(errout) + fmt.Println(err) } ``` - - ### GetOsBits +获取当前操作系统位数,返回32或64
函数签名: @@ -244,20 +242,17 @@ func main() { ```go func GetOsBits() int ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - osBit := system.GetOsBits() - fmt.Println(osBit) + osBit := system.GetOsBits() + fmt.Println(osBit) } ``` - - - - diff --git a/docs/system_zh-CN.md b/docs/system_zh-CN.md index f0acb3a..b00e68e 100644 --- a/docs/system_zh-CN.md +++ b/docs/system_zh-CN.md @@ -1,5 +1,6 @@ # System -system包含os, runtime, shell command相关函数。 + +system 包含 os, runtime, shell command 相关函数。 @@ -7,10 +8,10 @@ system包含os, runtime, shell command相关函数。 [https://github.com/duke-git/lancet/blob/v1/system/os.go](https://github.com/duke-git/lancet/blob/v1/system/os.go) - ## 用法: + ```go import ( "github.com/duke-git/lancet/system" @@ -20,23 +21,23 @@ import ( ## 目录 -- [IsWindows](#IsWindows) -- [IsLinux](#IsLinux) -- [IsMac](#IsMac) -- [GetOsEnv](#GetOsEnv) -- [SetOsEnv](#SetOsEnv) -- [RemoveOsEnv](#RemoveOsEnv) -- [CompareOsEnv](#CompareOsEnv) -- [ExecCommand](#ExecCommand) -- [GetOsBits](#GetOsBits) - + +- [IsWindows](#IsWindows) +- [IsLinux](#IsLinux) +- [IsMac](#IsMac) +- [GetOsEnv](#GetOsEnv) +- [SetOsEnv](#SetOsEnv) +- [RemoveOsEnv](#RemoveOsEnv) +- [CompareOsEnv](#CompareOsEnv) +- [ExecCommand](#ExecCommand) +- [GetOsBits](#GetOsBits) -## Documentation文档 - +## Documentation 文档 ### IsWindows +检查当前操作系统是否是windows
Signature: @@ -44,24 +45,23 @@ import ( ```go func IsWindows() bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - isOsWindows := system.IsWindows() - fmt.Println(isOsWindows) + isOsWindows := system.IsWindows() + fmt.Println(isOsWindows) } ``` - - - ### IsLinux +检查当前操作系统是否是linux
Signature: @@ -69,23 +69,23 @@ func main() { ```go func IsLinux() bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - isOsLinux := system.IsLinux() - fmt.Println(isOsLinux) + isOsLinux := system.IsLinux() + fmt.Println(isOsLinux) } ``` - - ### IsMac +检查当前操作系统是否是macos
Signature: @@ -93,23 +93,23 @@ func main() { ```go func IsMac() bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - isOsMac := system.IsMac - fmt.Println(isOsMac) + isOsMac := system.IsMac + fmt.Println(isOsMac) } ``` - - ### GetOsEnv +获取key命名的环境变量的值
Signature: @@ -117,23 +117,23 @@ func main() { ```go func GetOsEnv(key string) string ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - fooEnv := system.GetOsEnv("foo") - fmt.Println(fooEnv) + fooEnv := system.GetOsEnv("foo") + fmt.Println(fooEnv) } ``` - - ### SetOsEnv +设置由key命名的环境变量的值
Signature: @@ -141,24 +141,23 @@ func main() { ```go func SetOsEnv(key, value string) error ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - err := system.SetOsEnv("foo", "foo_value") - fmt.Println(err) + err := system.SetOsEnv("foo", "foo_value") + fmt.Println(err) } ``` - - - ### RemoveOsEnv +删除单个环境变量
Signature: @@ -166,25 +165,25 @@ func main() { ```go func RemoveOsEnv(key string) error ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - err := system.RemoveOsEnv("foo") - if err != nil { - fmt.Println(err) - } + err := system.RemoveOsEnv("foo") + if err != nil { + fmt.Println(err) + } } ``` - - ### CompareOsEnv +获取key命名的环境变量值并与compareEnv进行比较
Signature: @@ -192,25 +191,24 @@ func main() { ```go func CompareOsEnv(key, comparedEnv string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - system.SetOsEnv("foo", "foo_value") - res := system.CompareOsEnv("foo", "foo_value") - fmt.Println(res) //true + system.SetOsEnv("foo", "foo_value") + res := system.CompareOsEnv("foo", "foo_value") + fmt.Println(res) //true } ``` - - - ### CompareOsEnv +使用shell /bin/bash -c(linux) 或 cmd (windows) 执行shell命令
Signature: @@ -218,25 +216,25 @@ func main() { ```go func ExecCommand(command string) (stdout, stderr string, err error) ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - out, errout, err := system.ExecCommand("ls") - fmt.Println(out) - fmt.Println(errout) - fmt.Println(err) + out, errout, err := system.ExecCommand("ls") + fmt.Println(out) + fmt.Println(errout) + fmt.Println(err) } ``` - - ### GetOsBits +Get current os bits, 32bit or 64bit. return 32 or 64
Signature: @@ -244,20 +242,17 @@ func main() { ```go func GetOsBits() int ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/system" + "fmt" + "github.com/duke-git/lancet/system" ) func main() { - osBit := system.GetOsBits() - fmt.Println(osBit) + osBit := system.GetOsBits() + fmt.Println(osBit) } ``` - - - - diff --git a/docs/validator.md b/docs/validator.md index f6127bd..7a88002 100644 --- a/docs/validator.md +++ b/docs/validator.md @@ -1,4 +1,5 @@ # Validator + Package validator contains some functions for data validation. @@ -7,10 +8,10 @@ Package validator contains some functions for data validation. [https://github.com/duke-git/lancet/blob/v1/validator/validator.go](https://github.com/duke-git/lancet/blob/v1/validator/validator.go) - ## Usage: + ```go import ( "github.com/duke-git/lancet/validator" @@ -20,41 +21,42 @@ import ( ## Index -- [ContainChinese](#ContainChinese) -- [ContainLetter](#ContainLetter) -- [ContainLower](#ContainLower) -- [ContainUpper](#ContainUpper) -- [IsAlpha](#IsAlpha) -- [IsAllUpper](#IsAllUpper) -- [IsAllLower](#IsAllLower) -- [IsBase64](#IsBase64) -- [IsChineseMobile](#IsChineseMobile) -- [IsChineseIdNum](#IsChineseIdNum) -- [IsChinesePhone](#IsChinesePhone) -- [IsCreditCard](#IsCreditCard) -- [IsDns](#IsDns) -- [IsEmail](#IsEmail) -- [IsEmptyString](#IsEmptyString) -- [IsFloatStr](#IsFloatStr) -- [IsNumberStr](#IsNumberStr) -- [IsJSON](#IsJSON) -- [IsRegexMatch](#IsRegexMatch) -- [IsIntStr](#IsIntStr) -- [IsIp](#IsIp) -- [IsIpV4](#IsIpV4) -- [IsIpV6](#IsIpV6) -- [IsStrongPassword](#IsStrongPassword) -- [IsUrl](#IsUrl) -- [IsWeakPassword](#IsWeakPassword) -- [IsZeroValue](#IsZeroValue) -- [IsGBK](#IsGBK) + +- [ContainChinese](#ContainChinese) +- [ContainLetter](#ContainLetter) +- [ContainLower](#ContainLower) +- [ContainUpper](#ContainUpper) +- [IsAlpha](#IsAlpha) +- [IsAllUpper](#IsAllUpper) +- [IsAllLower](#IsAllLower) +- [IsBase64](#IsBase64) +- [IsChineseMobile](#IsChineseMobile) +- [IsChineseIdNum](#IsChineseIdNum) +- [IsChinesePhone](#IsChinesePhone) +- [IsCreditCard](#IsCreditCard) +- [IsDns](#IsDns) +- [IsEmail](#IsEmail) +- [IsEmptyString](#IsEmptyString) +- [IsFloatStr](#IsFloatStr) +- [IsNumberStr](#IsNumberStr) +- [IsJSON](#IsJSON) +- [IsRegexMatch](#IsRegexMatch) +- [IsIntStr](#IsIntStr) +- [IsIp](#IsIp) +- [IsIpV4](#IsIpV4) +- [IsIpV6](#IsIpV6) +- [IsStrongPassword](#IsStrongPassword) +- [IsUrl](#IsUrl) +- [IsWeakPassword](#IsWeakPassword) +- [IsZeroValue](#IsZeroValue) +- [IsGBK](#IsGBK) ## Documentation - ### ContainChinese +Check if the string contain mandarin chinese.
Signature: @@ -62,29 +64,29 @@ import ( ```go func ContainChinese(s string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainChinese("你好") - fmt.Println(res1) //true + res1 := validator.ContainChinese("你好") + fmt.Println(res1) //true - res2 := validator.ContainChinese("你好hello") - fmt.Println(res2) //true + res2 := validator.ContainChinese("你好hello") + fmt.Println(res2) //true - res3 := validator.ContainChinese("hello") - fmt.Println(res3) //false + res3 := validator.ContainChinese("hello") + fmt.Println(res3) //false } ``` - - ### ContainLetter +Check if the string contain at least one letter.
Signature: @@ -92,30 +94,29 @@ func main() { ```go func ContainLetter(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainLetter("1bc") - fmt.Println(res1) //true + res1 := validator.ContainLetter("1bc") + fmt.Println(res1) //true - res2 := validator.ContainLetter("123") - fmt.Println(res2) //false + res2 := validator.ContainLetter("123") + fmt.Println(res2) //false - res3 := validator.ContainLetter("&@#$%^&*") - fmt.Println(res3) //false + res3 := validator.ContainLetter("&@#$%^&*") + fmt.Println(res3) //false } ``` - - - ### ContainLower +Check if the string contain at least one lower case letter a-z.
Signature: @@ -123,30 +124,29 @@ func main() { ```go func ContainLower(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainLower("1bc") - fmt.Println(res1) //true + res1 := validator.ContainLower("1bc") + fmt.Println(res1) //true - res2 := validator.ContainLower("123") - fmt.Println(res2) //false + res2 := validator.ContainLower("123") + fmt.Println(res2) //false - res3 := validator.ContainLower("1BC") - fmt.Println(res3) //false + res3 := validator.ContainLower("1BC") + fmt.Println(res3) //false } ``` - - - ### ContainUpper +Check if the string contain at least one upper case letter A-Z.
Signature: @@ -154,30 +154,29 @@ func main() { ```go func ContainUpper(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainUpper("1bc") - fmt.Println(res1) //false + res1 := validator.ContainUpper("1bc") + fmt.Println(res1) //false - res2 := validator.ContainUpper("123") - fmt.Println(res2) //false + res2 := validator.ContainUpper("123") + fmt.Println(res2) //false - res3 := validator.ContainUpper("1BC") - fmt.Println(res3) //true + res3 := validator.ContainUpper("1BC") + fmt.Println(res3) //true } ``` - - - ### IsAlpha +Check if the string contains only letters (a-zA-Z).
Signature: @@ -185,27 +184,29 @@ func main() { ```go func IsAlpha(s string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsAlpha("abc") - fmt.Println(res1) //true + res1 := validator.IsAlpha("abc") + fmt.Println(res1) //true - res2 := validator.IsAlpha("1bc") - fmt.Println(res2) //false + res2 := validator.IsAlpha("1bc") + fmt.Println(res2) //false - res3 := validator.IsAlpha("") - fmt.Println(res3) //false + res3 := validator.IsAlpha("") + fmt.Println(res3) //false } ``` ### IsAllUpper +Check if string is all upper case letters A-Z.
Signature: @@ -213,27 +214,26 @@ func main() { ```go func IsAllUpper(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsAllUpper("ABC") - fmt.Println(res1) //true + res1 := validator.IsAllUpper("ABC") + fmt.Println(res1) //true - res2 := validator.IsAllUpper("aBC") - fmt.Println(res2) //false + res2 := validator.IsAllUpper("aBC") + fmt.Println(res2) //false } ``` - - - ### IsAllLower +Check if string is all lower case letters a-z.
Signature: @@ -241,27 +241,26 @@ func main() { ```go func IsAllLower(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsAllLower("abc") - fmt.Println(res1) //true + res1 := validator.IsAllLower("abc") + fmt.Println(res1) //true - res2 := validator.IsAllLower("abC") - fmt.Println(res2) //false + res2 := validator.IsAllLower("abC") + fmt.Println(res2) //false } ``` - - - ### IsBase64 +Check if the string is base64 string.
Signature: @@ -269,27 +268,26 @@ func main() { ```go func IsBase64(base64 string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsBase64("aGVsbG8=") - fmt.Println(res1) //true + res1 := validator.IsBase64("aGVsbG8=") + fmt.Println(res1) //true - res2 := validator.IsBase64("123456") - fmt.Println(res2) //false + res2 := validator.IsBase64("123456") + fmt.Println(res2) //false } ``` - - - ### IsChineseMobile +Check if the string is valid chinese mobile number.
Signature: @@ -297,26 +295,26 @@ func main() { ```go func IsChineseMobile(mobileNum string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsChineseMobile("13263527980") - fmt.Println(res1) //true + res1 := validator.IsChineseMobile("13263527980") + fmt.Println(res1) //true - res2 := validator.IsChineseMobile("434324324") - fmt.Println(res2) //false + res2 := validator.IsChineseMobile("434324324") + fmt.Println(res2) //false } ``` - - ### IsChineseIdNum +Check if the string is chinese id number.
Signature: @@ -324,27 +322,26 @@ func main() { ```go func IsChineseIdNum(id string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsChineseIdNum("210911192105130715") - fmt.Println(res1) //true + res1 := validator.IsChineseIdNum("210911192105130715") + fmt.Println(res1) //true - res2 := validator.IsChineseIdNum("123456") - fmt.Println(res2) //false + res2 := validator.IsChineseIdNum("123456") + fmt.Println(res2) //false } ``` - - - ### IsChinesePhone +Check if the string is chinese phone number.
Signature: @@ -352,27 +349,26 @@ func main() { ```go func IsChinesePhone(phone string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsChinesePhone("010-32116675") - fmt.Println(res1) //true + res1 := validator.IsChinesePhone("010-32116675") + fmt.Println(res1) //true - res2 := validator.IsChinesePhone("123-87562") - fmt.Println(res2) //false + res2 := validator.IsChinesePhone("123-87562") + fmt.Println(res2) //false } ``` - - - ### IsCreditCard +Check if the string is credit card.
Signature: @@ -380,27 +376,26 @@ func main() { ```go func IsCreditCard(creditCart string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsCreditCard("4111111111111111") - fmt.Println(res1) //true + res1 := validator.IsCreditCard("4111111111111111") + fmt.Println(res1) //true - res2 := validator.IsCreditCard("123456") - fmt.Println(res2) //false + res2 := validator.IsCreditCard("123456") + fmt.Println(res2) //false } ``` - - - ### IsDns +Check if the string is valid dns.
Signature: @@ -408,30 +403,29 @@ func main() { ```go func IsDns(dns string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsDns("abc.com") - fmt.Println(res1) //true + res1 := validator.IsDns("abc.com") + fmt.Println(res1) //true - res2 := validator.IsDns("a.b.com") - fmt.Println(res2) //false + res2 := validator.IsDns("a.b.com") + fmt.Println(res2) //false - res3 := validator.IsDns("http://abc.com") - fmt.Println(res3) //false + res3 := validator.IsDns("http://abc.com") + fmt.Println(res3) //false } ``` - - - ### IsEmail +Check if the string is email address.
Signature: @@ -439,28 +433,26 @@ func main() { ```go func IsEmail(email string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsEmail("abc@xyz.com") - fmt.Println(res1) //true + res1 := validator.IsEmail("abc@xyz.com") + fmt.Println(res1) //true - res2 := validator.IsEmail("a.b@@com") - fmt.Println(res2) //false + res2 := validator.IsEmail("a.b@@com") + fmt.Println(res2) //false } ``` - - - - ### IsEmptyString +Check if the string is empty or not.
Signature: @@ -468,27 +460,26 @@ func main() { ```go func IsEmptyString(s string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsEmptyString("") - fmt.Println(res1) //true + res1 := validator.IsEmptyString("") + fmt.Println(res1) //true - res2 := validator.IsEmptyString("abc") - fmt.Println(res2) //false + res2 := validator.IsEmptyString("abc") + fmt.Println(res2) //false } ``` - - - ### IsFloatStr +Check if the string can convert to a float.
Signature: @@ -496,28 +487,27 @@ func main() { ```go func IsFloatStr(s string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsFloatStr("")) //false - fmt.Println(validator.IsFloatStr("12a")) //false - fmt.Println(validator.IsFloatStr("3.")) //true - fmt.Println(validator.IsFloatStr("+3.")) //true - fmt.Println(validator.IsFloatStr("-3.")) //true - fmt.Println(validator.IsFloatStr("12")) //true + fmt.Println(validator.IsFloatStr("")) //false + fmt.Println(validator.IsFloatStr("12a")) //false + fmt.Println(validator.IsFloatStr("3.")) //true + fmt.Println(validator.IsFloatStr("+3.")) //true + fmt.Println(validator.IsFloatStr("-3.")) //true + fmt.Println(validator.IsFloatStr("12")) //true } ``` - - - ### IsNumberStr +Check if the string can convert to a number.
Signature: @@ -525,28 +515,27 @@ func main() { ```go func IsNumberStr(s string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsNumberStr("")) //false - fmt.Println(validator.IsNumberStr("12a")) //false - fmt.Println(validator.IsNumberStr("3.")) //true - fmt.Println(validator.IsNumberStr("+3.")) //true - fmt.Println(validator.IsNumberStr("-3.")) //true - fmt.Println(validator.IsNumberStr("+3e2")) //true + fmt.Println(validator.IsNumberStr("")) //false + fmt.Println(validator.IsNumberStr("12a")) //false + fmt.Println(validator.IsNumberStr("3.")) //true + fmt.Println(validator.IsNumberStr("+3.")) //true + fmt.Println(validator.IsNumberStr("-3.")) //true + fmt.Println(validator.IsNumberStr("+3e2")) //true } ``` - - - ### IsJSON +Check if the string is valid JSON.
Signature: @@ -554,28 +543,27 @@ func main() { ```go func IsJSON(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsJSON("")) //false - fmt.Println(validator.IsJSON("abc")) //false - fmt.Println(validator.IsJSON("{}")) //true - fmt.Println(validator.IsJSON("[]")) //true - fmt.Println(validator.IsJSON("123")) //true - fmt.Println(validator.IsJSON("{\"name\": \"test\"}")) //true + fmt.Println(validator.IsJSON("")) //false + fmt.Println(validator.IsJSON("abc")) //false + fmt.Println(validator.IsJSON("{}")) //true + fmt.Println(validator.IsJSON("[]")) //true + fmt.Println(validator.IsJSON("123")) //true + fmt.Println(validator.IsJSON("{\"name\": \"test\"}")) //true } ``` - - - ### IsRegexMatch +Check if the string match the regexp.
Signature: @@ -583,25 +571,24 @@ func main() { ```go func IsRegexMatch(s, regex string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsRegexMatch("abc", `^[a-zA-Z]+$`)) //true - fmt.Println(validator.IsRegexMatch("1ab", `^[a-zA-Z]+$`)) //false - fmt.Println(validator.IsRegexMatch("", `^[a-zA-Z]+$`)) //false + fmt.Println(validator.IsRegexMatch("abc", `^[a-zA-Z]+$`)) //true + fmt.Println(validator.IsRegexMatch("1ab", `^[a-zA-Z]+$`)) //false + fmt.Println(validator.IsRegexMatch("", `^[a-zA-Z]+$`)) //false } ``` - - - ### IsIntStr +Check if the string can convert to a integer.
Signature: @@ -609,26 +596,25 @@ func main() { ```go func IsIntStr(s string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIntStr("+3")) //true - fmt.Println(validator.IsIntStr("-3")) //true - fmt.Println(validator.IsIntStr("3.")) //false - fmt.Println(validator.IsIntStr("abc")) //false + fmt.Println(validator.IsIntStr("+3")) //true + fmt.Println(validator.IsIntStr("-3")) //true + fmt.Println(validator.IsIntStr("3.")) //false + fmt.Println(validator.IsIntStr("abc")) //false } ``` - - - ### IsIp +Check if the string is a ip address.
Signature: @@ -636,26 +622,25 @@ func main() { ```go func IsIp(ipstr string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIp("127.0.0.1")) //true - fmt.Println(validator.IsIp("::0:0:0:0:0:0:1")) //true - fmt.Println(validator.IsIp("127.0.0")) //false - fmt.Println(validator.IsIp("127")) //false + fmt.Println(validator.IsIp("127.0.0.1")) //true + fmt.Println(validator.IsIp("::0:0:0:0:0:0:1")) //true + fmt.Println(validator.IsIp("127.0.0")) //false + fmt.Println(validator.IsIp("127")) //false } ``` - - - ### IsIpV4 +Check if the string is a ipv4 address.
Signature: @@ -663,26 +648,25 @@ func main() { ```go func IsIpV4(ipstr string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIpV4("127.0.0.1")) //true - fmt.Println(validator.IsIpV4("::0:0:0:0:0:0:1")) //false - fmt.Println(validator.IsIpV4("127.0.0")) //false - fmt.Println(validator.IsIpV4("127")) //false + fmt.Println(validator.IsIpV4("127.0.0.1")) //true + fmt.Println(validator.IsIpV4("::0:0:0:0:0:0:1")) //false + fmt.Println(validator.IsIpV4("127.0.0")) //false + fmt.Println(validator.IsIpV4("127")) //false } ``` - - - ### IsIpV6 +Check if the string is a ipv6 address.
Signature: @@ -690,26 +674,25 @@ func main() { ```go func IsIpV6(ipstr string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIpV6("127.0.0.1")) //false - fmt.Println(validator.IsIpV6("::0:0:0:0:0:0:1")) //true - fmt.Println(validator.IsIpV6("127.0.0")) //false - fmt.Println(validator.IsIpV6("127")) //false + fmt.Println(validator.IsIpV6("127.0.0.1")) //false + fmt.Println(validator.IsIpV6("::0:0:0:0:0:0:1")) //true + fmt.Println(validator.IsIpV6("127.0.0")) //false + fmt.Println(validator.IsIpV6("127")) //false } ``` - - - ### IsStrongPassword +Check if the string is strong password (alpha(lower+upper) + number + special chars(!@#$%^&*()?><)).
Signature: @@ -717,54 +700,52 @@ func main() { ```go func IsStrongPassword(password string, length int) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsStrongPassword("abc", 3)) //false - fmt.Println(validator.IsStrongPassword("abc123", 6)) //false - fmt.Println(validator.IsStrongPassword("abcABC", 6)) //false - fmt.Println(validator.IsStrongPassword("abcABC123@#$", 16)) //false - fmt.Println(validator.IsStrongPassword("abcABC123@#$", 12)) //true + fmt.Println(validator.IsStrongPassword("abc", 3)) //false + fmt.Println(validator.IsStrongPassword("abc123", 6)) //false + fmt.Println(validator.IsStrongPassword("abcABC", 6)) //false + fmt.Println(validator.IsStrongPassword("abcABC123@#$", 16)) //false + fmt.Println(validator.IsStrongPassword("abcABC123@#$", 12)) //true } ``` - - - ### IsUrl +Check if the string is url.
Signature: ```go -func IsUrl(str string) bool +func IsUrl(str string) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsUrl("http://abc.com")) //true - fmt.Println(validator.IsUrl("abc.com")) //true - fmt.Println(validator.IsUrl("a.b.com")) //true - fmt.Println(validator.IsUrl("abc")) //false + fmt.Println(validator.IsUrl("http://abc.com")) //true + fmt.Println(validator.IsUrl("abc.com")) //true + fmt.Println(validator.IsUrl("a.b.com")) //true + fmt.Println(validator.IsUrl("abc")) //false } ``` - - - ### IsWeakPassword +Check if the string is weak password(only letter or only number or letter + number) .
@@ -773,23 +754,25 @@ func main() { ```go func IsWeakPassword(password string, length int) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsWeakPassword("abc")) //true - fmt.Println(validator.IsWeakPassword("123")) //true - fmt.Println(validator.IsWeakPassword("abc123")) //true - fmt.Println(validator.IsWeakPassword("abc123@#$")) //false + fmt.Println(validator.IsWeakPassword("abc")) //true + fmt.Println(validator.IsWeakPassword("123")) //true + fmt.Println(validator.IsWeakPassword("abc123")) //true + fmt.Println(validator.IsWeakPassword("abc123@#$")) //false } ``` ### IsZeroValue +Checks if passed value is a zero value.
Signature: @@ -797,29 +780,29 @@ func main() { ```go func IsZeroValue(value any) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsZeroValue(nil)) //true - fmt.Println(validator.IsZeroValue(0)) //true - fmt.Println(validator.IsZeroValue("")) //true - fmt.Println(validator.IsZeroValue([]int)) //true - fmt.Println(validator.IsZeroValue(interface{})) //true + fmt.Println(validator.IsZeroValue(nil)) //true + fmt.Println(validator.IsZeroValue(0)) //true + fmt.Println(validator.IsZeroValue("")) //true + fmt.Println(validator.IsZeroValue([]int)) //true + fmt.Println(validator.IsZeroValue(interface{})) //true - fmt.Println(validator.IsZeroValue("0")) //false - fmt.Println(validator.IsZeroValue("nil")) //false + fmt.Println(validator.IsZeroValue("0")) //false + fmt.Println(validator.IsZeroValue("nil")) //false } ``` - - ### IsGBK +Checks if data encoding is gbk(Chinese character internal code extension specification). this function is implemented by whether double bytes fall within the encoding range of gbk,while each byte of utf-8 encoding format falls within the encoding range of gbk.Therefore, utf8.valid() should be called first to check whether it is not utf-8 encoding and then call IsGBK() to check gbk encoding. like the example.
Signature: @@ -827,31 +810,24 @@ func main() { ```go func IsGBK(data []byte) bool ``` + Example: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - data := []byte("你好") - - // check utf8 first - if utf8.Valid(data) { - fmt.Println("data encoding is utf-8") - }else if(validator.IsGBK(data)) { - fmt.Println("data encoding is GBK") - } - fmt.Println("data encoding is unknown") + data := []byte("你好") + + // check utf8 first + if utf8.Valid(data) { + fmt.Println("data encoding is utf-8") + }else if(validator.IsGBK(data)) { + fmt.Println("data encoding is GBK") + } + fmt.Println("data encoding is unknown") } ``` - - - - - - - - diff --git a/docs/validator_zh-CN.md b/docs/validator_zh-CN.md index a283f64..9882e1f 100644 --- a/docs/validator_zh-CN.md +++ b/docs/validator_zh-CN.md @@ -1,5 +1,6 @@ # Validator -validator验证器包,包含常用字符串格式验证函数。 + +validator 验证器包,包含常用字符串格式验证函数。 @@ -7,10 +8,10 @@ validator验证器包,包含常用字符串格式验证函数。 [https://github.com/duke-git/lancet/blob/v1/validator/validator.go](https://github.com/duke-git/lancet/blob/v1/validator/validator.go) - ## 用法: + ```go import ( "github.com/duke-git/lancet/validator" @@ -20,41 +21,42 @@ import ( ## 目录: -- [ContainChinese](#ContainChinese) -- [ContainLetter](#ContainLetter) -- [ContainLower](#ContainLower) -- [ContainUpper](#ContainUpper) -- [IsAlpha](#IsAlpha) -- [IsAllUpper](#IsAllUpper) -- [IsAllLower](#IsAllLower) -- [IsBase64](#IsBase64) -- [IsChineseMobile](#IsChineseMobile) -- [IsChineseIdNum](#IsChineseIdNum) -- [IsChinesePhone](#IsChinesePhone) -- [IsCreditCard](#IsCreditCard) -- [IsDns](#IsDns) -- [IsEmail](#IsEmail) -- [IsEmptyString](#IsEmptyString) -- [IsFloatStr](#IsFloatStr) -- [IsNumberStr](#IsNumberStr) -- [IsJSON](#IsJSON) -- [IsRegexMatch](#IsRegexMatch) -- [IsIntStr](#IsIntStr) -- [IsIp](#IsIp) -- [IsIpV4](#IsIpV4) -- [IsIpV6](#IsIpV6) -- [IsStrongPassword](#IsStrongPassword) -- [IsUrl](#IsUrl) -- [IsWeakPassword](#IsWeakPassword) -- [IsZeroValue](#IsZeroValue) -- [IsGBK](#IsGBK) + +- [ContainChinese](#ContainChinese) +- [ContainLetter](#ContainLetter) +- [ContainLower](#ContainLower) +- [ContainUpper](#ContainUpper) +- [IsAlpha](#IsAlpha) +- [IsAllUpper](#IsAllUpper) +- [IsAllLower](#IsAllLower) +- [IsBase64](#IsBase64) +- [IsChineseMobile](#IsChineseMobile) +- [IsChineseIdNum](#IsChineseIdNum) +- [IsChinesePhone](#IsChinesePhone) +- [IsCreditCard](#IsCreditCard) +- [IsDns](#IsDns) +- [IsEmail](#IsEmail) +- [IsEmptyString](#IsEmptyString) +- [IsFloatStr](#IsFloatStr) +- [IsNumberStr](#IsNumberStr) +- [IsJSON](#IsJSON) +- [IsRegexMatch](#IsRegexMatch) +- [IsIntStr](#IsIntStr) +- [IsIp](#IsIp) +- [IsIpV4](#IsIpV4) +- [IsIpV6](#IsIpV6) +- [IsStrongPassword](#IsStrongPassword) +- [IsUrl](#IsUrl) +- [IsWeakPassword](#IsWeakPassword) +- [IsZeroValue](#IsZeroValue) +- [IsGBK](#IsGBK) ## 文档 - ### ContainChinese +验证字符串是否包含中文字符
函数签名: @@ -62,29 +64,29 @@ import ( ```go func ContainChinese(s string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainChinese("你好") - fmt.Println(res1) //true + res1 := validator.ContainChinese("你好") + fmt.Println(res1) //true - res2 := validator.ContainChinese("你好hello") - fmt.Println(res2) //true + res2 := validator.ContainChinese("你好hello") + fmt.Println(res2) //true - res3 := validator.ContainChinese("hello") - fmt.Println(res3) //false + res3 := validator.ContainChinese("hello") + fmt.Println(res3) //false } ``` - - ### ContainLetter +验证字符串是否包含至少一个英文字母
函数签名: @@ -92,30 +94,29 @@ func main() { ```go func ContainLetter(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainLetter("1bc") - fmt.Println(res1) //true + res1 := validator.ContainLetter("1bc") + fmt.Println(res1) //true - res2 := validator.ContainLetter("123") - fmt.Println(res2) //false + res2 := validator.ContainLetter("123") + fmt.Println(res2) //false - res3 := validator.ContainLetter("&@#$%^&*") - fmt.Println(res3) //false + res3 := validator.ContainLetter("&@#$%^&*") + fmt.Println(res3) //false } ``` - - - ### ContainLower +验证字符串是否包含至少一个英文小写字母
函数签名: @@ -123,30 +124,29 @@ func main() { ```go func ContainLower(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainLower("1bc") - fmt.Println(res1) //true + res1 := validator.ContainLower("1bc") + fmt.Println(res1) //true - res2 := validator.ContainLower("123") - fmt.Println(res2) //false + res2 := validator.ContainLower("123") + fmt.Println(res2) //false - res3 := validator.ContainLower("1BC") - fmt.Println(res3) //false + res3 := validator.ContainLower("1BC") + fmt.Println(res3) //false } ``` - - - ### ContainUpper +验证字符串是否包含至少一个英文大写字母.
函数签名: @@ -154,30 +154,29 @@ func main() { ```go func ContainUpper(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.ContainUpper("1bc") - fmt.Println(res1) //false + res1 := validator.ContainUpper("1bc") + fmt.Println(res1) //false - res2 := validator.ContainUpper("123") - fmt.Println(res2) //false + res2 := validator.ContainUpper("123") + fmt.Println(res2) //false - res3 := validator.ContainUpper("1BC") - fmt.Println(res3) //true + res3 := validator.ContainUpper("1BC") + fmt.Println(res3) //true } ``` - - - ### IsAlpha +验证字符串是否只包含英文字母
函数签名: @@ -185,27 +184,29 @@ func main() { ```go func IsAlpha(s string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsAlpha("abc") - fmt.Println(res1) //true + res1 := validator.IsAlpha("abc") + fmt.Println(res1) //true - res2 := validator.IsAlpha("1bc") - fmt.Println(res2) //false + res2 := validator.IsAlpha("1bc") + fmt.Println(res2) //false - res3 := validator.IsAlpha("") - fmt.Println(res3) //false + res3 := validator.IsAlpha("") + fmt.Println(res3) //false } ``` ### IsAllUpper +验证字符串是否全是大写英文字母
函数签名: @@ -213,27 +214,26 @@ func main() { ```go func IsAllUpper(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsAllUpper("ABC") - fmt.Println(res1) //true + res1 := validator.IsAllUpper("ABC") + fmt.Println(res1) //true - res2 := validator.IsAllUpper("aBC") - fmt.Println(res2) //false + res2 := validator.IsAllUpper("aBC") + fmt.Println(res2) //false } ``` - - - ### IsAllLower +验证字符串是否全是小写英文字母
函数签名: @@ -241,27 +241,26 @@ func main() { ```go func IsAllLower(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsAllLower("abc") - fmt.Println(res1) //true + res1 := validator.IsAllLower("abc") + fmt.Println(res1) //true - res2 := validator.IsAllLower("abC") - fmt.Println(res2) //false + res2 := validator.IsAllLower("abC") + fmt.Println(res2) //false } ``` - - - ### IsBase64 +验证字符串是否是base64编码
函数签名: @@ -269,27 +268,26 @@ func main() { ```go func IsBase64(base64 string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsBase64("aGVsbG8=") - fmt.Println(res1) //true + res1 := validator.IsBase64("aGVsbG8=") + fmt.Println(res1) //true - res2 := validator.IsBase64("123456") - fmt.Println(res2) //false + res2 := validator.IsBase64("123456") + fmt.Println(res2) //false } ``` - - - ### IsChineseMobile +验证字符串是否是中国手机号码
函数签名: @@ -297,26 +295,26 @@ func main() { ```go func IsChineseMobile(mobileNum string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsChineseMobile("13263527980") - fmt.Println(res1) //true + res1 := validator.IsChineseMobile("13263527980") + fmt.Println(res1) //true - res2 := validator.IsChineseMobile("434324324") - fmt.Println(res2) //false + res2 := validator.IsChineseMobile("434324324") + fmt.Println(res2) //false } ``` - - ### IsChineseIdNum +验证字符串是否是中国身份证号码
函数签名: @@ -324,27 +322,26 @@ func main() { ```go func IsChineseIdNum(id string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsChineseIdNum("210911192105130715") - fmt.Println(res1) //true + res1 := validator.IsChineseIdNum("210911192105130715") + fmt.Println(res1) //true - res2 := validator.IsChineseIdNum("123456") - fmt.Println(res2) //false + res2 := validator.IsChineseIdNum("123456") + fmt.Println(res2) //false } ``` - - - ### IsChinesePhone +验证字符串是否是中国电话座机号码
函数签名: @@ -352,27 +349,26 @@ func main() { ```go func IsChinesePhone(phone string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsChinesePhone("010-32116675") - fmt.Println(res1) //true + res1 := validator.IsChinesePhone("010-32116675") + fmt.Println(res1) //true - res2 := validator.IsChinesePhone("123-87562") - fmt.Println(res2) //false + res2 := validator.IsChinesePhone("123-87562") + fmt.Println(res2) //false } ``` - - - ### IsCreditCard +验证字符串是否是信用卡号码
函数签名: @@ -380,27 +376,26 @@ func main() { ```go func IsCreditCard(creditCart string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsCreditCard("4111111111111111") - fmt.Println(res1) //true + res1 := validator.IsCreditCard("4111111111111111") + fmt.Println(res1) //true - res2 := validator.IsCreditCard("123456") - fmt.Println(res2) //false + res2 := validator.IsCreditCard("123456") + fmt.Println(res2) //false } ``` - - - ### IsDns +验证字符串是否是有效dns
函数签名: @@ -408,30 +403,29 @@ func main() { ```go func IsDns(dns string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsDns("abc.com") - fmt.Println(res1) //true + res1 := validator.IsDns("abc.com") + fmt.Println(res1) //true - res2 := validator.IsDns("a.b.com") - fmt.Println(res2) //false + res2 := validator.IsDns("a.b.com") + fmt.Println(res2) //false - res3 := validator.IsDns("http://abc.com") - fmt.Println(res3) //false + res3 := validator.IsDns("http://abc.com") + fmt.Println(res3) //false } ``` - - - ### IsEmail +验证字符串是否是有效电子邮件地址
函数签名: @@ -439,28 +433,26 @@ func main() { ```go func IsEmail(email string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsEmail("abc@xyz.com") - fmt.Println(res1) //true + res1 := validator.IsEmail("abc@xyz.com") + fmt.Println(res1) //true - res2 := validator.IsEmail("a.b@@com") - fmt.Println(res2) //false + res2 := validator.IsEmail("a.b@@com") + fmt.Println(res2) //false } ``` - - - - ### IsEmptyString +验证字符串是否是空字符串
函数签名: @@ -468,27 +460,26 @@ func main() { ```go func IsEmptyString(s string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - res1 := validator.IsEmptyString("") - fmt.Println(res1) //true + res1 := validator.IsEmptyString("") + fmt.Println(res1) //true - res2 := validator.IsEmptyString("abc") - fmt.Println(res2) //false + res2 := validator.IsEmptyString("abc") + fmt.Println(res2) //false } ``` - - - ### IsFloatStr +验证字符串是否是可以转换为浮点数
函数签名: @@ -496,28 +487,27 @@ func main() { ```go func IsFloatStr(s string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsFloatStr("")) //false - fmt.Println(validator.IsFloatStr("12a")) //false - fmt.Println(validator.IsFloatStr("3.")) //true - fmt.Println(validator.IsFloatStr("+3.")) //true - fmt.Println(validator.IsFloatStr("-3.")) //true - fmt.Println(validator.IsFloatStr("12")) //true + fmt.Println(validator.IsFloatStr("")) //false + fmt.Println(validator.IsFloatStr("12a")) //false + fmt.Println(validator.IsFloatStr("3.")) //true + fmt.Println(validator.IsFloatStr("+3.")) //true + fmt.Println(validator.IsFloatStr("-3.")) //true + fmt.Println(validator.IsFloatStr("12")) //true } ``` - - - ### IsNumberStr +验证字符串是否是可以转换为数字
函数签名: @@ -525,28 +515,27 @@ func main() { ```go func IsNumberStr(s string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsNumberStr("")) //false - fmt.Println(validator.IsNumberStr("12a")) //false - fmt.Println(validator.IsNumberStr("3.")) //true - fmt.Println(validator.IsNumberStr("+3.")) //true - fmt.Println(validator.IsNumberStr("-3.")) //true - fmt.Println(validator.IsNumberStr("+3e2")) //true + fmt.Println(validator.IsNumberStr("")) //false + fmt.Println(validator.IsNumberStr("12a")) //false + fmt.Println(validator.IsNumberStr("3.")) //true + fmt.Println(validator.IsNumberStr("+3.")) //true + fmt.Println(validator.IsNumberStr("-3.")) //true + fmt.Println(validator.IsNumberStr("+3e2")) //true } ``` - - - ### IsJSON +验证字符串是否是有效json
函数签名: @@ -554,28 +543,27 @@ func main() { ```go func IsJSON(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsJSON("")) //false - fmt.Println(validator.IsJSON("abc")) //false - fmt.Println(validator.IsJSON("{}")) //true - fmt.Println(validator.IsJSON("[]")) //true - fmt.Println(validator.IsJSON("123")) //true - fmt.Println(validator.IsJSON("{\"name\": \"test\"}")) //true + fmt.Println(validator.IsJSON("")) //false + fmt.Println(validator.IsJSON("abc")) //false + fmt.Println(validator.IsJSON("{}")) //true + fmt.Println(validator.IsJSON("[]")) //true + fmt.Println(validator.IsJSON("123")) //true + fmt.Println(validator.IsJSON("{\"name\": \"test\"}")) //true } ``` - - - ### IsRegexMatch +验证字符串是否可以匹配正则表达式
函数签名: @@ -583,25 +571,24 @@ func main() { ```go func IsRegexMatch(s, regex string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsRegexMatch("abc", `^[a-zA-Z]+$`)) //true - fmt.Println(validator.IsRegexMatch("1ab", `^[a-zA-Z]+$`)) //false - fmt.Println(validator.IsRegexMatch("", `^[a-zA-Z]+$`)) //false + fmt.Println(validator.IsRegexMatch("abc", `^[a-zA-Z]+$`)) //true + fmt.Println(validator.IsRegexMatch("1ab", `^[a-zA-Z]+$`)) //false + fmt.Println(validator.IsRegexMatch("", `^[a-zA-Z]+$`)) //false } ``` - - - ### IsIntStr +验证字符串是否是可以转换为整数
函数签名: @@ -609,26 +596,25 @@ func main() { ```go func IsIntStr(s string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIntStr("+3")) //true - fmt.Println(validator.IsIntStr("-3")) //true - fmt.Println(validator.IsIntStr("3.")) //false - fmt.Println(validator.IsIntStr("abc")) //false + fmt.Println(validator.IsIntStr("+3")) //true + fmt.Println(validator.IsIntStr("-3")) //true + fmt.Println(validator.IsIntStr("3.")) //false + fmt.Println(validator.IsIntStr("abc")) //false } ``` - - - ### IsIp +验证字符串是否是ip地址
函数签名: @@ -636,26 +622,25 @@ func main() { ```go func IsIp(ipstr string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIp("127.0.0.1")) //true - fmt.Println(validator.IsIp("::0:0:0:0:0:0:1")) //true - fmt.Println(validator.IsIp("127.0.0")) //false - fmt.Println(validator.IsIp("127")) //false + fmt.Println(validator.IsIp("127.0.0.1")) //true + fmt.Println(validator.IsIp("::0:0:0:0:0:0:1")) //true + fmt.Println(validator.IsIp("127.0.0")) //false + fmt.Println(validator.IsIp("127")) //false } ``` - - - ### IsIpV4 +验证字符串是否是ipv4地址
函数签名: @@ -663,26 +648,25 @@ func main() { ```go func IsIpV4(ipstr string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIpV4("127.0.0.1")) //true - fmt.Println(validator.IsIpV4("::0:0:0:0:0:0:1")) //false - fmt.Println(validator.IsIpV4("127.0.0")) //false - fmt.Println(validator.IsIpV4("127")) //false + fmt.Println(validator.IsIpV4("127.0.0.1")) //true + fmt.Println(validator.IsIpV4("::0:0:0:0:0:0:1")) //false + fmt.Println(validator.IsIpV4("127.0.0")) //false + fmt.Println(validator.IsIpV4("127")) //false } ``` - - - ### IsIpV6 +验证字符串是否是ipv6地址
函数签名: @@ -690,26 +674,25 @@ func main() { ```go func IsIpV6(ipstr string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsIpV6("127.0.0.1")) //false - fmt.Println(validator.IsIpV6("::0:0:0:0:0:0:1")) //true - fmt.Println(validator.IsIpV6("127.0.0")) //false - fmt.Println(validator.IsIpV6("127")) //false + fmt.Println(validator.IsIpV6("127.0.0.1")) //false + fmt.Println(validator.IsIpV6("::0:0:0:0:0:0:1")) //true + fmt.Println(validator.IsIpV6("127.0.0")) //false + fmt.Println(validator.IsIpV6("127")) //false } ``` - - - ### IsStrongPassword +验证字符串是否是强密码:(alpha(lower+upper) + number + special chars(!@#$%^&*()?><))
函数签名: @@ -717,54 +700,52 @@ func main() { ```go func IsStrongPassword(password string, length int) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsStrongPassword("abc", 3)) //false - fmt.Println(validator.IsStrongPassword("abc123", 6)) //false - fmt.Println(validator.IsStrongPassword("abcABC", 6)) //false - fmt.Println(validator.IsStrongPassword("abcABC123@#$", 16)) //false - fmt.Println(validator.IsStrongPassword("abcABC123@#$", 12)) //true + fmt.Println(validator.IsStrongPassword("abc", 3)) //false + fmt.Println(validator.IsStrongPassword("abc123", 6)) //false + fmt.Println(validator.IsStrongPassword("abcABC", 6)) //false + fmt.Println(validator.IsStrongPassword("abcABC123@#$", 16)) //false + fmt.Println(validator.IsStrongPassword("abcABC123@#$", 12)) //true } ``` - - - ### IsUrl +验证字符串是否是url
函数签名: ```go -func IsUrl(str string) bool +func IsUrl(str string) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsUrl("http://abc.com")) //true - fmt.Println(validator.IsUrl("abc.com")) //true - fmt.Println(validator.IsUrl("a.b.com")) //true - fmt.Println(validator.IsUrl("abc")) //false + fmt.Println(validator.IsUrl("http://abc.com")) //true + fmt.Println(validator.IsUrl("abc.com")) //true + fmt.Println(validator.IsUrl("a.b.com")) //true + fmt.Println(validator.IsUrl("abc")) //false } ``` - - - ### IsWeakPassword +验证字符串是否是弱密码:(only letter or only number or letter + number) .
@@ -773,25 +754,25 @@ func main() { ```go func IsWeakPassword(password string, length int) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsWeakPassword("abc")) //true - fmt.Println(validator.IsWeakPassword("123")) //true - fmt.Println(validator.IsWeakPassword("abc123")) //true - fmt.Println(validator.IsWeakPassword("abc123@#$")) //false + fmt.Println(validator.IsWeakPassword("abc")) //true + fmt.Println(validator.IsWeakPassword("123")) //true + fmt.Println(validator.IsWeakPassword("abc123")) //true + fmt.Println(validator.IsWeakPassword("abc123@#$")) //false } ``` - - ### IsZeroValue +判断传入的参数值是否为零值
函数签名: @@ -799,29 +780,29 @@ func main() { ```go func IsZeroValue(value any) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - fmt.Println(validator.IsZeroValue(nil)) //true - fmt.Println(validator.IsZeroValue(0)) //true - fmt.Println(validator.IsZeroValue("")) //true - fmt.Println(validator.IsZeroValue([]int)) //true - fmt.Println(validator.IsZeroValue(interface{})) //true - - fmt.Println(validator.IsZeroValue("0")) //false - fmt.Println(validator.IsZeroValue("nil")) //false + fmt.Println(validator.IsZeroValue(nil)) //true + fmt.Println(validator.IsZeroValue(0)) //true + fmt.Println(validator.IsZeroValue("")) //true + fmt.Println(validator.IsZeroValue([]int)) //true + fmt.Println(validator.IsZeroValue(interface{})) //true + + fmt.Println(validator.IsZeroValue("0")) //false + fmt.Println(validator.IsZeroValue("nil")) //false } ``` - - ### IsGBK +检查数据编码是否为gbk(汉字内部代码扩展规范)。该函数的实现取决于双字节是否在gbk的编码范围内,而utf-8编码格式的每个字节都在gbk编码范围内。因此,应该首先调用utf8.valid检查它是否是utf-8编码,然后调用IsGBK检查gbk编码。如示例所示。
函数签名: @@ -829,25 +810,24 @@ func main() { ```go func IsGBK(data []byte) bool ``` + 例子: ```go import ( - "fmt" - "github.com/duke-git/lancet/validator" + "fmt" + "github.com/duke-git/lancet/validator" ) func main() { - data := []byte("你好") - - // 先检查utf8编码 - if utf8.Valid(data) { - fmt.Println("data encoding is utf-8") - }else if(validator.IsGBK(data)) { - fmt.Println("data encoding is GBK") - } - fmt.Println("data encoding is unknown") + data := []byte("你好") + + // 先检查utf8编码 + if utf8.Valid(data) { + fmt.Println("data encoding is utf-8") + }else if(validator.IsGBK(data)) { + fmt.Println("data encoding is GBK") + } + fmt.Println("data encoding is unknown") } ``` - -