1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

doc: format all markdown doc

This commit is contained in:
dudaodong
2023-02-23 10:36:54 +08:00
parent 15c1537bf0
commit 24eb2bbacd
26 changed files with 3396 additions and 3567 deletions

View File

@@ -1,4 +1,5 @@
# Convertor
Package convertor contains some functions for data type convertion.
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ Package convertor contains some functions for data type convertion.
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/convertor"
@@ -20,28 +22,27 @@ import (
## Index
- [ColorHexToRGB](#ColorHexToRGB)
- [ColorRGBToHex](#ColorRGBToHex)
- [ToBool](#ToBool)
- [ToBytes](#ToBytes)
- [ToChar](#ToChar)
- [ToChannel](#ToChannel)
- [ToFloat](#ToFloat)
- [ToInt](#ToInt)
- [ToJson](#ToJson)
- [ToString](#ToString)
- [StructToMap](#StructToMap)
- [EncodeByte](#EncodeByte)
- [DecodeByte](#DecodeByte)
- [DeepClone](#DeepClone)
- [ColorHexToRGB](#ColorHexToRGB)
- [ColorRGBToHex](#ColorRGBToHex)
- [ToBool](#ToBool)
- [ToBytes](#ToBytes)
- [ToChar](#ToChar)
- [ToChannel](#ToChannel)
- [ToFloat](#ToFloat)
- [ToInt](#ToInt)
- [ToJson](#ToJson)
- [ToString](#ToString)
- [StructToMap](#StructToMap)
- [EncodeByte](#EncodeByte)
- [DecodeByte](#DecodeByte)
- [DeepClone](#DeepClone)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="ColorHexToRGB">ColorHexToRGB</span>
<p>Convert color hex to color rgb.</p>
<b>Signature:</b>
@@ -49,6 +50,7 @@ import (
```go
func ColorHexToRGB(colorHex string) (red, green, blue int)
```
<b>Example:</b>
```go
@@ -66,8 +68,6 @@ func main() {
}
```
### <span id="ColorRGBToHex">ColorRGBToHex</span>
<p>Convert color rgb to color hex.</p>
@@ -77,6 +77,7 @@ func main() {
```go
func ColorRGBToHex(red, green, blue int) string
```
<b>Example:</b>
```go
@@ -97,8 +98,6 @@ func main() {
}
```
### <span id="ToBool">ToBool</span>
<p>Convert string to a boolean value. Use strconv.ParseBool</p>
@@ -108,6 +107,7 @@ func main() {
```go
func ToBool(s string) (bool, error)
```
<b>Example:</b>
```go
@@ -133,8 +133,6 @@ func main() {
}
```
### <span id="ToBytes">ToBytes</span>
<p>Convert interface to byte slice.</p>
@@ -144,6 +142,7 @@ func main() {
```go
func ToBytes(data interface{}) ([]byte, error)
```
<b>Example:</b>
```go
@@ -163,8 +162,6 @@ func main() {
}
```
### <span id="ToChar">ToChar</span>
<p>Convert string to char slice.</p>
@@ -174,6 +171,7 @@ func main() {
```go
func ToChar(s string) []string
```
<b>Example:</b>
```go
@@ -196,7 +194,6 @@ func main() {
}
```
### <span id="ToChannel">ToChannel</span>
<p>Convert a collection of elements to a read-only channels.</p>
@@ -206,6 +203,7 @@ func main() {
```go
func ToChannel(array []interface{}) <-chan interface{}
```
<b>Example:</b>
```go
@@ -233,8 +231,6 @@ func main() {
}
```
### <span id="ToFloat">ToFloat</span>
<p>Convert interface to a float64 value. If param is a invalid floatable, will return 0 and error. </p>
@@ -244,6 +240,7 @@ func main() {
```go
func ToFloat(value interface{}) (float64, error)
```
<b>Example:</b>
```go
@@ -266,8 +263,6 @@ func main() {
}
```
### <span id="ToInt">ToInt</span>
<p>Convert interface to a int64 value. If param is a invalid intable, will return 0 and error. </p>
@@ -277,6 +272,7 @@ func main() {
```go
func ToInt(value interface{}) (int64, error)
```
<b>Example:</b>
```go
@@ -299,8 +295,6 @@ func main() {
}
```
### <span id="ToJson">ToJson</span>
<p>Convert interface to json string. If param can't be converted, will return "" and error. </p>
@@ -310,6 +304,7 @@ func main() {
```go
func ToJson(value interface{}) (string, error)
```
<b>Example:</b>
```go
@@ -327,8 +322,6 @@ func main() {
}
```
### <span id="ToString">ToString</span>
<p>Convert interface to string. </p>
@@ -338,6 +331,7 @@ func main() {
```go
func ToString(value interface{}) string
```
<b>Example:</b>
```go
@@ -355,8 +349,6 @@ func main() {
}
```
### <span id="StructToMap">StructToMap</span>
<p>Convert struct to map, only convert exported field, struct field tag `json` should be set.</p>
@@ -366,6 +358,7 @@ func main() {
```go
func StructToMap(value interface{}) (map[string]interface{}, error)
```
<b>Example:</b>
```go
@@ -391,7 +384,6 @@ func main() {
}
```
### <span id="EncodeByte">EncodeByte</span>
<p>Encode data to byte slice.</p>
@@ -401,6 +393,7 @@ func main() {
```go
func EncodeByte(data any) ([]byte, error)
```
<b>Example:</b>
```go
@@ -417,8 +410,6 @@ func main() {
}
```
### <span id="DecodeByte">DecodeByte</span>
<p>Decode byte data to target object. target should be a pointer instance.</p>
@@ -428,6 +419,7 @@ func main() {
```go
func DecodeByte(data []byte, target any) error
```
<b>Example:</b>
```go
@@ -440,8 +432,8 @@ import (
func main() {
var result string
byteData := []byte{6, 12, 0, 3, 97, 98, 99}
convertor.DecodeByte(byteData, &result)
byteData := []byte{6, 12, 0, 3, 97, 98, 99}
convertor.DecodeByte(byteData, &result)
fmt.Println(result) //"abc"
}
```
@@ -468,44 +460,44 @@ import (
func main() {
type Struct struct {
Str string
Int int
Float float64
Bool bool
Nil interface{}
unexported string
}
Str string
Int int
Float float64
Bool bool
Nil interface{}
unexported string
}
cases := []interface{}{
true,
1,
0.1,
map[string]int{
"a": 1,
"b": 2,
},
&Struct{
Str: "test",
Int: 1,
Float: 0.1,
Bool: true,
Nil: nil,
// unexported: "can't be cloned",
},
}
cases := []interface{}{
true,
1,
0.1,
map[string]int{
"a": 1,
"b": 2,
},
&Struct{
Str: "test",
Int: 1,
Float: 0.1,
Bool: true,
Nil: nil,
// unexported: "can't be cloned",
},
}
for _, item := range cases {
cloned := convertor.DeepClone(item)
for _, item := range cases {
cloned := convertor.DeepClone(item)
isPointerEqual := &cloned == &item
fmt.Println(cloned, isPointerEqual)
}
isPointerEqual := &cloned == &item
fmt.Println(cloned, isPointerEqual)
}
// Output:
// true false
// 1 false
// 0.1 false
// map[a:1 b:2] false
// &{test 1 0.1 true <nil> } false
// Output:
// true false
// 1 false
// 0.1 false
// map[a:1 b:2] false
// &{test 1 0.1 true <nil> } false
}
```
```

View File

@@ -1,5 +1,6 @@
# Convertor
convertor转换器包支持一些常见的数据类型转换
convertor 转换器包支持一些常见的数据类型转换
<div STYLE="page-break-after: always;"></div>
@@ -21,28 +22,27 @@ import (
## 目录
- [ColorHexToRGB](#ColorHexToRGB)
- [ColorRGBToHex](#ColorRGBToHex)
- [ToBool](#ToBool)
- [ToBytes](#ToBytes)
- [ToChar](#ToChar)
- [ToChannel](#ToChannel)
- [ToFloat](#ToFloat)
- [ToInt](#ToInt)
- [ToJson](#ToJson)
- [ToString](#ToString)
- [StructToMap](#StructToMap)
- [EncodeByte](#EncodeByte)
- [DecodeByte](#DecodeByte)
- [DeepClone](#DeepClone)
- [ColorHexToRGB](#ColorHexToRGB)
- [ColorRGBToHex](#ColorRGBToHex)
- [ToBool](#ToBool)
- [ToBytes](#ToBytes)
- [ToChar](#ToChar)
- [ToChannel](#ToChannel)
- [ToFloat](#ToFloat)
- [ToInt](#ToInt)
- [ToJson](#ToJson)
- [ToString](#ToString)
- [StructToMap](#StructToMap)
- [EncodeByte](#EncodeByte)
- [DecodeByte](#DecodeByte)
- [DeepClone](#DeepClone)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="ColorHexToRGB">ColorHexToRGB</span>
<p>颜色值十六进制转rgb</p>
<b>函数签名:</b>
@@ -50,6 +50,7 @@ import (
```go
func ColorHexToRGB(colorHex string) (red, green, blue int)
```
<b>列子:</b>
```go
@@ -67,8 +68,6 @@ func main() {
}
```
### <span id="ColorRGBToHex">ColorRGBToHex</span>
<p>颜色值rgb转十六进制</p>
@@ -78,6 +77,7 @@ func main() {
```go
func ColorRGBToHex(red, green, blue int) string
```
<b>列子:</b>
```go
@@ -98,8 +98,6 @@ func main() {
}
```
### <span id="ToBool">ToBool</span>
<p>字符串转布尔类型使用strconv.ParseBool</p>
@@ -109,6 +107,7 @@ func main() {
```go
func ToBool(s string) (bool, error)
```
<b>列子:</b>
```go
@@ -134,8 +133,6 @@ func main() {
}
```
### <span id="ToBytes">ToBytes</span>
<p>interface转字节切片.</p>
@@ -145,6 +142,7 @@ func main() {
```go
func ToBytes(data interface{}) ([]byte, error)
```
<b>列子:</b>
```go
@@ -164,8 +162,6 @@ func main() {
}
```
### <span id="ToChar">ToChar</span>
<p>字符串转字符切片</p>
@@ -175,6 +171,7 @@ func main() {
```go
func ToChar(s string) []string
```
<b>列子:</b>
```go
@@ -197,8 +194,6 @@ func main() {
}
```
### <span id="ToChannel">ToChannel</span>
<p>将切片转为只读channel</p>
@@ -208,6 +203,7 @@ func main() {
```go
func ToChannel(array []interface{}) <-chan interface{}
```
<b>例子:</b>
```go
@@ -235,8 +231,6 @@ func main() {
}
```
### <span id="ToFloat">ToFloat</span>
<p>将interface转成float64类型如果参数无法转换会返回0和error</p>
@@ -246,6 +240,7 @@ func main() {
```go
func ToFloat(value interface{}) (float64, error)
```
<b>列子:</b>
```go
@@ -268,8 +263,6 @@ func main() {
}
```
### <span id="ToInt">ToInt</span>
<p>将interface转成intt64类型如果参数无法转换会返回0和error</p>
@@ -279,6 +272,7 @@ func main() {
```go
func ToInt(value interface{}) (int64, error)
```
<b>例子:</b>
```go
@@ -301,8 +295,6 @@ func main() {
}
```
### <span id="ToJson">ToJson</span>
<p>将interface转成json字符串如果参数无法转换会返回""和error</p>
@@ -312,6 +304,7 @@ func main() {
```go
func ToJson(value interface{}) (string, error)
```
<b>列子:</b>
```go
@@ -329,8 +322,6 @@ func main() {
}
```
### <span id="ToString">ToString</span>
<p>将interface转成字符串</p>
@@ -340,6 +331,7 @@ func main() {
```go
func ToString(value interface{}) string
```
<b>例子:</b>
```go
@@ -357,8 +349,6 @@ func main() {
}
```
### <span id="StructToMap">StructToMap</span>
<p>将struct转成map只会转换struct中可导出的字段。struct中导出字段需要设置json tag标记</p>
@@ -368,6 +358,7 @@ func main() {
```go
func StructToMap(value interface{}) (map[string]interface{}, error)
```
<b>列子:</b>
```go
@@ -393,7 +384,6 @@ func main() {
}
```
### <span id="EncodeByte">EncodeByte</span>
<p>将data编码成字节切片</p>
@@ -403,6 +393,7 @@ func main() {
```go
func EncodeByte(data any) ([]byte, error)
```
<b>例子:</b>
```go
@@ -419,8 +410,6 @@ func main() {
}
```
### <span id="DecodeByte">DecodeByte</span>
<p>解码字节切片到目标对象,目标对象需要传入一个指针实例子</p>
@@ -430,6 +419,7 @@ func main() {
```go
func DecodeByte(data []byte, target any) error
```
<b>例子:</b>
```go
@@ -442,13 +432,12 @@ import (
func main() {
var result string
byteData := []byte{6, 12, 0, 3, 97, 98, 99}
convertor.DecodeByte(byteData, &result)
byteData := []byte{6, 12, 0, 3, 97, 98, 99}
convertor.DecodeByte(byteData, &result)
fmt.Println(result) //"abc"
}
```
### <span id="DeepClone">DeepClone</span>
<p>创建一个传入值的深拷贝, 无法克隆结构体的非导出字段。</p>
@@ -471,44 +460,44 @@ import (
func main() {
type Struct struct {
Str string
Int int
Float float64
Bool bool
Nil interface{}
unexported string
}
Str string
Int int
Float float64
Bool bool
Nil interface{}
unexported string
}
cases := []interface{}{
true,
1,
0.1,
map[string]int{
"a": 1,
"b": 2,
},
&Struct{
Str: "test",
Int: 1,
Float: 0.1,
Bool: true,
Nil: nil,
// unexported: "can't be cloned",
},
}
cases := []interface{}{
true,
1,
0.1,
map[string]int{
"a": 1,
"b": 2,
},
&Struct{
Str: "test",
Int: 1,
Float: 0.1,
Bool: true,
Nil: nil,
// unexported: "can't be cloned",
},
}
for _, item := range cases {
cloned := convertor.DeepClone(item)
for _, item := range cases {
cloned := convertor.DeepClone(item)
isPointerEqual := &cloned == &item
fmt.Println(cloned, isPointerEqual)
}
isPointerEqual := &cloned == &item
fmt.Println(cloned, isPointerEqual)
}
// Output:
// true false
// 1 false
// 0.1 false
// map[a:1 b:2] false
// &{test 1 0.1 true <nil> } false
// Output:
// true false
// 1 false
// 0.1 false
// map[a:1 b:2] false
// &{test 1 0.1 true <nil> } false
}
```
```

View File

@@ -1,18 +1,20 @@
# Cryptor
Package cryptor contains some functions for data encryption and decryption. Support base64, md5, hmac, aes, des, rsa.
<div STYLE="page-break-after: always;"></div>
## Source:
- [https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go](https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/des.go](https://github.com/duke-git/lancet/blob/v1/cryptor/des.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go](https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go](https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go](https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/des.go](https://github.com/duke-git/lancet/blob/v1/cryptor/des.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go](https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go](https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/cryptor"
@@ -23,46 +25,43 @@ import (
## Index
- [AesEcbEncrypt](#AesEcbEncrypt)
- [AesEcbDecrypt](#AesEcbDecrypt)
- [AesCbcEncrypt](#AesCbcEncrypt)
- [AesCbcDecrypt](#AesCbcDecrypt)
- [AesCtrCrypt](#AesCtrCrypt)
- [AesCfbEncrypt](#AesCfbEncrypt)
- [AesCfbDecrypt](#AesCfbDecrypt)
- [AesOfbEncrypt](#AesOfbEncrypt)
- [AesOfbDecrypt](#AesOfbDecrypt)
- [Base64StdEncode](#Base64StdEncode)
- [Base64StdDecode](#Base64StdDecode)
- [DesEcbEncrypt](#DesEcbEncrypt)
- [DesEcbDecrypt](#DesEcbDecrypt)
- [DesCbcEncrypt](#DesCbcEncrypt)
- [DesCbcDecrypt](#DesCbcDecrypt)
- [DesCtrCrypt](#DesCtrCrypt)
- [DesCfbEncrypt](#DesCfbEncrypt)
- [DesCfbDecrypt](#DesCfbDecrypt)
- [DesOfbEncrypt](#DesOfbEncrypt)
- [DesOfbDecrypt](#DesOfbDecrypt)
- [HmacMd5](#HmacMd5)
- [HmacSha1](#HmacSha1)
- [HmacSha256](#HmacSha256)
- [HmacSha512](#HmacSha512)
- [Md5String](#Md5String)
- [Md5File](#Md5File)
- [Sha1](#Sha1)
- [Sha256](#Sha256)
- [Sha512](#Sha512)
- [GenerateRsaKey](#GenerateRsaKey)
- [RsaEncrypt](#RsaEncrypt)
- [RsaDecrypt](#RsaDecrypt)
- [AesEcbEncrypt](#AesEcbEncrypt)
- [AesEcbDecrypt](#AesEcbDecrypt)
- [AesCbcEncrypt](#AesCbcEncrypt)
- [AesCbcDecrypt](#AesCbcDecrypt)
- [AesCtrCrypt](#AesCtrCrypt)
- [AesCfbEncrypt](#AesCfbEncrypt)
- [AesCfbDecrypt](#AesCfbDecrypt)
- [AesOfbEncrypt](#AesOfbEncrypt)
- [AesOfbDecrypt](#AesOfbDecrypt)
- [Base64StdEncode](#Base64StdEncode)
- [Base64StdDecode](#Base64StdDecode)
- [DesEcbEncrypt](#DesEcbEncrypt)
- [DesEcbDecrypt](#DesEcbDecrypt)
- [DesCbcEncrypt](#DesCbcEncrypt)
- [DesCbcDecrypt](#DesCbcDecrypt)
- [DesCtrCrypt](#DesCtrCrypt)
- [DesCfbEncrypt](#DesCfbEncrypt)
- [DesCfbDecrypt](#DesCfbDecrypt)
- [DesOfbEncrypt](#DesOfbEncrypt)
- [DesOfbDecrypt](#DesOfbDecrypt)
- [HmacMd5](#HmacMd5)
- [HmacSha1](#HmacSha1)
- [HmacSha256](#HmacSha256)
- [HmacSha512](#HmacSha512)
- [Md5String](#Md5String)
- [Md5File](#Md5File)
- [Sha1](#Sha1)
- [Sha256](#Sha256)
- [Sha512](#Sha512)
- [GenerateRsaKey](#GenerateRsaKey)
- [RsaEncrypt](#RsaEncrypt)
- [RsaDecrypt](#RsaDecrypt)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="AesEcbEncrypt">AesEcbEncrypt</span>
<p>Encrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -72,6 +71,7 @@ import (
```go
func AesEcbEncrypt(data, key []byte) []byte
```
<b>Example:</b>
```go
@@ -84,15 +84,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesEcbDecrypt">AesEcbDecrypt</span>
<p>Decrypt data with key use AES ECB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -102,6 +100,7 @@ func main() {
```go
func AesEcbDecrypt(encrypted, key []byte) []byte
```
<b>Example:</b>
```go
@@ -114,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
}
```
### <span id="AesCbcEncrypt">AesCbcEncrypt</span>
<p>Encrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -132,6 +129,7 @@ func main() {
```go
func AesCbcEncrypt(data, key []byte) []byte
```
<b>Example:</b>
```go
@@ -144,15 +142,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesCbcDecrypt">AesCbcDecrypt</span>
<p>Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -175,15 +171,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="AesCtrCrypt">AesCtrCrypt</span>
<p>Encrypt or decrypt data with key use AES CTR algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -206,7 +200,7 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCtrCrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCtrCrypt(encrypted, []byte(key))
@@ -214,8 +208,6 @@ func main() {
}
```
### <span id="AesCfbEncrypt">AesCfbEncrypt</span>
<p>Encrypt data with key use AES CFB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -238,14 +230,12 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesCfbDecrypt">AesCfbDecrypt</span>
<p>Decrypt data with key use AES CBC algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -270,13 +260,11 @@ func main() {
data := "hello world"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="AesOfbEncrypt">AesOfbEncrypt</span>
<p>Enecrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -299,14 +287,12 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesCfbDecrypt">AesOfbDecrypt</span>
<p>Decrypt data with key use AES OFB algorithm. Length of `key` param should be 16, 24 or 32.</p>
@@ -329,16 +315,14 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesOfbDecrypt(encrypted, []byte(key))
decrypted := cryptor.AesOfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="Base64StdEncode">Base64StdEncode</span>
<p>Encode string with base64 encoding.</p>
@@ -348,6 +332,7 @@ func main() {
```go
func Base64StdEncode(s string) string
```
<b>Example:</b>
```go
@@ -359,13 +344,11 @@ import (
)
func main() {
base64Str := cryptor.Base64StdEncode("hello world")
base64Str := cryptor.Base64StdEncode("hello world")
fmt.Println(base64Str) //aGVsbG8gd29ybGQ=
}
```
### <span id="Base64StdDecode">Base64StdDecode</span>
<p>Decode a base64 encoded string.</p>
@@ -392,8 +375,6 @@ func main() {
}
```
### <span id="DesEcbEncrypt">DesEcbEncrypt</span>
<p>Encrypt data with key use DES ECB algorithm. Length of `key` param should be 8.</p>
@@ -416,15 +397,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="DesEcbDecrypt">DesEcbDecrypt</span>
<p>Decrypt data with key use DES ECB algorithm. Length of `key` param should be 8.</p>
@@ -447,16 +426,14 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byt(key)
decrypted := cryptor.DesEcbDecrypt(encrypted, []byte(key))
decrypted := cryptor.DesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="DesCbcEncrypt">DesCbcEncrypt</span>
<p>Encrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p>
@@ -479,15 +456,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCbcEncrypt([]byte(data), []byt(key)
fmt.Println(string(encrypted))
}
```
### <span id="DesCbcDecrypt">DesCbcDecrypt</span>
<p>Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p>
@@ -510,16 +485,14 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCbcEncrypt([]byte(data), []byt(key)
decrypted := cryptor.DesCbcDecrypt(encrypted, []byte(key))
decrypted := cryptor.DesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="DesCtrCrypt">DesCtrCrypt</span>
<p>Encrypt or decrypt data with key use DES CTR algorithm. Length of `key` param should be 8.</p>
@@ -542,7 +515,7 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCtrCrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCtrCrypt(encrypted, []byte(key))
@@ -550,8 +523,6 @@ func main() {
}
```
### <span id="DesCfbEncrypt">DesCfbEncrypt</span>
<p>Encrypt data with key use DES CFB algorithm. Length of `key` param should be 8.</p>
@@ -574,14 +545,12 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byt(key)
fmt.Println(string(encrypted))
}
```
### <span id="DesCfbDecrypt">DesCfbDecrypt</span>
<p>Decrypt data with key use DES CBC algorithm. Length of `key` param should be 8.</p>
@@ -604,15 +573,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byt(key)
decrypted := cryptor.DesCfbDecrypt(encrypted, []byte(key))
decrypted := cryptor.DesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="DesOfbEncrypt">DesOfbEncrypt</span>
<p>Enecrypt data with key use DES OFB algorithm. Length of `key` param should be 8.</p>
@@ -635,14 +602,12 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="DesOfbDecrypt">DesOfbDecrypt</span>
<p>Decrypt data with key use DES OFB algorithm. Length of `key` param should be 8.</p>
@@ -665,16 +630,14 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesOfbDecrypt(encrypted, []byte(key))
decrypted := cryptor.DesOfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="HmacMd5">HmacMd5</span>
<p>Get the md5 hmac hash of string.</p>
@@ -696,13 +659,11 @@ import (
)
func main() {
s := cryptor.HmacMd5("hello world", "12345"))
fmt.Println(s) //5f4c9faaff0a1ad3007d9ddc06abe36d
s := cryptor.HmacMd5("hello world", "12345"))
fmt.Println(s) //5f4c9faaff0a1ad3007d9ddc06abe36d
}
```
### <span id="HmacSha1">HmacSha1</span>
<p>Get the sha1 hmac hash of string.</p>
@@ -724,13 +685,11 @@ import (
)
func main() {
s := cryptor.HmacSha1("hello world", "12345"))
fmt.Println(s) //3826f812255d8683f051ee97346d1359234d5dbd
s := cryptor.HmacSha1("hello world", "12345"))
fmt.Println(s) //3826f812255d8683f051ee97346d1359234d5dbd
}
```
### <span id="HmacSha256">HmacSha256</span>
<p>Get the sha256 hmac hash of string</p>
@@ -752,13 +711,11 @@ import (
)
func main() {
s := cryptor.HmacSha256("hello world", "12345"))
fmt.Println(s) //9dce2609f2d67d41f74c7f9efc8ccd44370d41ad2de52982627588dfe7289ab8
s := cryptor.HmacSha256("hello world", "12345"))
fmt.Println(s) //9dce2609f2d67d41f74c7f9efc8ccd44370d41ad2de52982627588dfe7289ab8
}
```
### <span id="HmacSha512">HmacSha512</span>
<p>Get the sha512 hmac hash of string.</p>
@@ -780,14 +737,11 @@ import (
)
func main() {
s := cryptor.HmacSha512("hello world", "12345"))
fmt.Println(s)
//5b1563ac4e9b49c9ada8ccb232588fc4f0c30fd12f756b3a0b95af4985c236ca60925253bae10ce2c6bf9af1c1679b51e5395ff3d2826c0a2c7c0d72225d4175
s := cryptor.HmacSha512("hello world", "12345"))
fmt.Println(s) //5b1563ac4e9b49c9ada8ccb232588fc4f0c30fd12f756b3a0b95af4985c236ca60925253bae10ce2c6bf9af1c1679b51e5395ff3d2826c0a2c7c0d72225d4175
}
```
### <span id="Md5String">Md5String</span>
<p>Get the md5 value of string.</p>
@@ -809,13 +763,11 @@ import (
)
func main() {
s := cryptor.Md5String("hello"))
fmt.Println(s) //5d41402abc4b2a76b9719d911017c592
s := cryptor.Md5String("hello"))
fmt.Println(s) //5d41402abc4b2a76b9719d911017c592
}
```
### <span id="Md5File">Md5File</span>
<p>Get the md5 value of file.</p>
@@ -837,13 +789,11 @@ import (
)
func main() {
s := cryptor.Md5File("./main.go"))
fmt.Println(s)
s := cryptor.Md5File("./main.go"))
fmt.Println(s)
}
```
### <span id="Sha1">Sha1</span>
<p>Get the sha1 value of string.</p>
@@ -865,13 +815,11 @@ import (
)
func main() {
s := cryptor.Sha1("hello world"))
fmt.Println(s) //2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
s := cryptor.Sha1("hello world"))
fmt.Println(s) //2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
}
```
### <span id="Sha256">Sha256</span>
<p>Get the sha256 value of string.</p>
@@ -893,13 +841,11 @@ import (
)
func main() {
s := cryptor.Sha256("hello world"))
fmt.Println(s) //b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
s := cryptor.Sha256("hello world"))
fmt.Println(s) //b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
}
```
### <span id="Sha512">Sha512</span>
<p>Get the sha512 value of string.</p>
@@ -921,13 +867,11 @@ import (
)
func main() {
s := cryptor.Sha512("hello world"))
s := cryptor.Sha512("hello world"))
fmt.Println(s) //309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f
}
```
### <span id="GenerateRsaKey">GenerateRsaKey</span>
<p>Create the rsa public and private key file in current directory.</p>
@@ -949,15 +893,13 @@ import (
)
func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
}
}
```
### <span id="RsaEncrypt">RsaEncrypt</span>
<p>Encrypt data with public key file useing ras algorithm.</p>
@@ -979,21 +921,19 @@ import (
)
func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
data := []byte("hello world")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="RsaDecrypt">RsaDecrypt</span>
<p>Decrypt data with private key file useing ras algorithm.</p>
@@ -1015,18 +955,15 @@ import (
)
func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
}
data := []byte("hello world")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
fmt.Println(string(decrypted)) //hello world
}
```

View File

@@ -1,18 +1,20 @@
# Cryptor
cryptor加密包支持数据加密和解密获取md5hash值。支持base64, md5, hmac, aes, des, rsa。
cryptor 加密包支持数据加密和解密,获取 md5hash 值。支持 base64, md5, hmac, aes, des, rsa。
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go](https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/des.go](https://github.com/duke-git/lancet/blob/v1/cryptor/des.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go](https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go](https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go](https://github.com/duke-git/lancet/blob/v1/cryptor/aes.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/des.go](https://github.com/duke-git/lancet/blob/v1/cryptor/des.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go](https://github.com/duke-git/lancet/blob/v1/cryptor/basic.go)
- [https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go](https://github.com/duke-git/lancet/blob/v1/cryptor/rsa.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/cryptor"
@@ -22,46 +24,44 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [AesEcbEncrypt](#AesEcbEncrypt)
- [AesEcbDecrypt](#AesEcbDecrypt)
- [AesCbcEncrypt](#AesCbcEncrypt)
- [AesCbcDecrypt](#AesCbcDecrypt)
- [AesCtrCrypt](#AesCtrCrypt)
- [AesCfbEncrypt](#AesCfbEncrypt)
- [AesCfbDecrypt](#AesCfbDecrypt)
- [AesOfbEncrypt](#AesOfbEncrypt)
- [AesOfbDecrypt](#AesOfbDecrypt)
- [Base64StdEncode](#Base64StdEncode)
- [Base64StdDecode](#Base64StdDecode)
- [DesEcbEncrypt](#DesEcbEncrypt)
- [DesEcbDecrypt](#DesEcbDecrypt)
- [DesCbcEncrypt](#DesCbcEncrypt)
- [DesCbcDecrypt](#DesCbcDecrypt)
- [DesCtrCrypt](#DesCtrCrypt)
- [DesCfbEncrypt](#DesCfbEncrypt)
- [DesCfbDecrypt](#DesCfbDecrypt)
- [DesOfbEncrypt](#DesOfbEncrypt)
- [DesOfbDecrypt](#DesOfbDecrypt)
- [HmacMd5](#HmacMd5)
- [HmacSha1](#HmacSha1)
- [HmacSha256](#HmacSha256)
- [HmacSha512](#HmacSha512)
- [Md5String](#Md5String)
- [Md5File](#Md5File)
- [Sha1](#Sha1)
- [Sha256](#Sha256)
- [Sha512](#Sha512)
- [GenerateRsaKey](#GenerateRsaKey)
- [RsaEncrypt](#RsaEncrypt)
- [RsaDecrypt](#RsaDecrypt)
- [AesEcbEncrypt](#AesEcbEncrypt)
- [AesEcbDecrypt](#AesEcbDecrypt)
- [AesCbcEncrypt](#AesCbcEncrypt)
- [AesCbcDecrypt](#AesCbcDecrypt)
- [AesCtrCrypt](#AesCtrCrypt)
- [AesCfbEncrypt](#AesCfbEncrypt)
- [AesCfbDecrypt](#AesCfbDecrypt)
- [AesOfbEncrypt](#AesOfbEncrypt)
- [AesOfbDecrypt](#AesOfbDecrypt)
- [Base64StdEncode](#Base64StdEncode)
- [Base64StdDecode](#Base64StdDecode)
- [DesEcbEncrypt](#DesEcbEncrypt)
- [DesEcbDecrypt](#DesEcbDecrypt)
- [DesCbcEncrypt](#DesCbcEncrypt)
- [DesCbcDecrypt](#DesCbcDecrypt)
- [DesCtrCrypt](#DesCtrCrypt)
- [DesCfbEncrypt](#DesCfbEncrypt)
- [DesCfbDecrypt](#DesCfbDecrypt)
- [DesOfbEncrypt](#DesOfbEncrypt)
- [DesOfbDecrypt](#DesOfbDecrypt)
- [HmacMd5](#HmacMd5)
- [HmacSha1](#HmacSha1)
- [HmacSha256](#HmacSha256)
- [HmacSha512](#HmacSha512)
- [Md5String](#Md5String)
- [Md5File](#Md5File)
- [Sha1](#Sha1)
- [Sha256](#Sha256)
- [Sha512](#Sha512)
- [GenerateRsaKey](#GenerateRsaKey)
- [RsaEncrypt](#RsaEncrypt)
- [RsaDecrypt](#RsaDecrypt)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="AesEcbEncrypt">AesEcbEncrypt</span>
<p>使用AES ECB算法模式加密数据. 参数`key`的长度是16, 24 or 32。</p>
@@ -71,6 +71,7 @@ import (
```go
func AesEcbEncrypt(data, key []byte) []byte
```
<b>列子:</b>
```go
@@ -83,15 +84,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesEcbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesEcbDecrypt">AesEcbDecrypt</span>
<p>使用AES ECB算法模式解密数据. 参数`key`的长度是16, 24 or 32。
@@ -101,6 +100,7 @@ func main() {
```go
func AesEcbDecrypt(encrypted, key []byte) []byte
```
<b>列子:</b>
```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
}
```
### <span id="AesCbcEncrypt">AesCbcEncrypt</span>
<p>使用AES CBC算法模式加密数据. 参数`key`的长度是16, 24 or 32。</p>
@@ -131,6 +129,7 @@ func main() {
```go
func AesCbcEncrypt(data, key []byte) []byte
```
<b>列子:</b>
```go
@@ -143,15 +142,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesCbcDecrypt">AesCbcDecrypt</span>
<p>使用AES CBC算法模式解密数据. 参数`key`的长度是16, 24 or 32。</p>
@@ -174,16 +171,14 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="AesCtrCrypt">AesCtrCrypt</span>
<p>使用AES CTR算法模式加密/解密数据. 参数`key`的长度是16, 24 or 32。</p>
@@ -206,7 +201,7 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCtrCrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCtrCrypt(encrypted, []byte(key))
@@ -214,8 +209,6 @@ func main() {
}
```
### <span id="AesCfbEncrypt">AesCfbEncrypt</span>
<p>使用AES CFB算法模式加密数据. 参数`key`的长度是16, 24 or 32。</p>
@@ -238,14 +231,12 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesCfbDecrypt">AesCfbDecrypt</span>
<p>使用AES CFB算法模式解密数据. 参数`key`的长度是16, 24 or 32。</p>
@@ -268,15 +259,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
decrypted := cryptor.AesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="AesOfbEncrypt">AesOfbEncrypt</span>
<p>使用AES OFB算法模式加密数据. 参数`key`的长度是16, 24 or 32</p>
@@ -299,14 +288,12 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="AesCfbDecrypt">AesOfbDecrypt</span>
<p>使用AES OFB算法模式解密数据. 参数`key`的长度是16, 24 or 32</p>
@@ -329,15 +316,13 @@ import (
func main() {
data := "hello world"
key := "abcdefghijklmnop"
key := "abcdefghijklmnop"
encrypted := cryptor.AesOfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesOfbDecrypt(encrypted, []byte(key))
decrypted := cryptor.AesOfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="Base64StdEncode">Base64StdEncode</span>
<p>将字符串base64编码</p>
@@ -347,6 +332,7 @@ func main() {
```go
func Base64StdEncode(s string) string
```
<b>列子:</b>
```go
@@ -358,13 +344,11 @@ import (
)
func main() {
base64Str := cryptor.Base64StdEncode("hello world")
base64Str := cryptor.Base64StdEncode("hello world")
fmt.Println(base64Str) //aGVsbG8gd29ybGQ=
}
```
### <span id="Base64StdDecode">Base64StdDecode</span>
<p>解码base64字符串</p>
@@ -386,13 +370,11 @@ import (
)
func main() {
str := cryptor.Base64StdDecode("aGVsbG8gd29ybGQ=")
str := cryptor.Base64StdDecode("aGVsbG8gd29ybGQ=")
fmt.Println(str) //hello world
}
```
### <span id="DesEcbEncrypt">DesEcbEncrypt</span>
<p>使用DES ECB算法模式加密数据. 参数`key`的长度是8</p>
@@ -415,15 +397,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="DesEcbDecrypt">DesEcbDecrypt</span>
<p>使用DES ECB算法模式解密数据. 参数`key`的长度是8</p>
@@ -446,16 +426,14 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesEcbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesEcbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="DesCbcEncrypt">DesCbcEncrypt</span>
<p>使用DES CBC算法模式加密数据. 参数`key`的长度是8</p>
@@ -478,15 +456,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCbcEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="DesCbcDecrypt">DesCbcDecrypt</span>
<p>使用DES CBC算法模式解密数据. 参数`key`的长度是8</p>
@@ -509,16 +485,14 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="DesCtrCrypt">DesCtrCrypt</span>
<p>使用DES CTR算法模式加密/解密数据. 参数`key`的长度是8</p>
@@ -541,7 +515,7 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCtrCrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCtrCrypt(encrypted, []byte(key))
@@ -549,8 +523,6 @@ func main() {
}
```
### <span id="DesCfbEncrypt">DesCfbEncrypt</span>
<p>使用DES CFB算法模式加密数据. 参数`key`的长度是8</p>
@@ -573,14 +545,12 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="DesCfbDecrypt">DesCfbDecrypt</span>
<p>使用DES CFB算法模式解密数据. 参数`key`的长度是8</p>
@@ -603,15 +573,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesCfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesCfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="DesOfbEncrypt">DesOfbEncrypt</span>
<p>使用DES OFB算法模式加密数据. 参数`key`的长度是8</p>
@@ -634,14 +602,12 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key))
fmt.Println(string(encrypted))
}
```
### <span id="DesOfbDecrypt">DesOfbDecrypt</span>
<p>使用DES OFB算法模式解密数据. 参数`key`的长度是8</p>
@@ -664,15 +630,13 @@ import (
func main() {
data := "hello world"
key := "abcdefgh"
key := "abcdefgh"
encrypted := cryptor.DesOfbEncrypt([]byte(data), []byte(key))
decrypted := cryptor.DesOfbDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="HmacMd5">HmacMd5</span>
<p>获取字符串md5 hmac值</p>
@@ -694,13 +658,11 @@ import (
)
func main() {
s := cryptor.HmacMd5("hello world", "12345"))
fmt.Println(s) //5f4c9faaff0a1ad3007d9ddc06abe36d
s := cryptor.HmacMd5("hello world", "12345"))
fmt.Println(s) //5f4c9faaff0a1ad3007d9ddc06abe36d
}
```
### <span id="HmacSha1">HmacSha1</span>
<p>获取字符串sha1 hmac值</p>
@@ -722,13 +684,11 @@ import (
)
func main() {
s := cryptor.HmacSha1("hello world", "12345"))
fmt.Println(s) //3826f812255d8683f051ee97346d1359234d5dbd
s := cryptor.HmacSha1("hello world", "12345"))
fmt.Println(s) //3826f812255d8683f051ee97346d1359234d5dbd
}
```
### <span id="HmacSha256">HmacSha256</span>
<p>获取字符串sha256 hmac值</p>
@@ -750,13 +710,11 @@ import (
)
func main() {
s := cryptor.HmacSha256("hello world", "12345"))
fmt.Println(s) //9dce2609f2d67d41f74c7f9efc8ccd44370d41ad2de52982627588dfe7289ab8
s := cryptor.HmacSha256("hello world", "12345"))
fmt.Println(s) //9dce2609f2d67d41f74c7f9efc8ccd44370d41ad2de52982627588dfe7289ab8
}
```
### <span id="HmacSha512">HmacSha512</span>
<p>获取字符串sha512 hmac值</p>
@@ -778,14 +736,12 @@ import (
)
func main() {
s := cryptor.HmacSha512("hello world", "12345"))
fmt.Println(s)
s := cryptor.HmacSha512("hello world", "12345"))
fmt.Println(s)
//5b1563ac4e9b49c9ada8ccb232588fc4f0c30fd12f756b3a0b95af4985c236ca60925253bae10ce2c6bf9af1c1679b51e5395ff3d2826c0a2c7c0d72225d4175
}
```
### <span id="Md5String">Md5String</span>
<p>获取字符串md5值</p>
@@ -807,13 +763,11 @@ import (
)
func main() {
s := cryptor.Md5String("hello"))
fmt.Println(s) //5d41402abc4b2a76b9719d911017c592
s := cryptor.Md5String("hello"))
fmt.Println(s) //5d41402abc4b2a76b9719d911017c592
}
```
### <span id="Md5File">Md5File</span>
<p>获取文件md5值.</p>
@@ -835,13 +789,11 @@ import (
)
func main() {
s := cryptor.Md5File("./main.go"))
fmt.Println(s)
s := cryptor.Md5File("./main.go"))
fmt.Println(s)
}
```
### <span id="Sha1">Sha1</span>
<p>获取字符串sha1值</p>
@@ -863,13 +815,11 @@ import (
)
func main() {
s := cryptor.Sha1("hello world"))
fmt.Println(s) //2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
s := cryptor.Sha1("hello world"))
fmt.Println(s) //2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
}
```
### <span id="Sha256">Sha256</span>
<p>获取字符串sha256值</p>
@@ -891,13 +841,11 @@ import (
)
func main() {
s := cryptor.Sha256("hello world"))
fmt.Println(s) //b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
s := cryptor.Sha256("hello world"))
fmt.Println(s) //b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
}
```
### <span id="Sha512">Sha512</span>
<p>获取字符串sha512值</p>
@@ -919,13 +867,11 @@ import (
)
func main() {
s := cryptor.Sha512("hello world"))
fmt.Println(s) //309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f
s := cryptor.Sha512("hello world"))
fmt.Println(s) //309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f
}
```
### <span id="GenerateRsaKey">GenerateRsaKey</span>
<p>在当前目录下创建rsa私钥文件和公钥文件</p>
@@ -947,15 +893,13 @@ import (
)
func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
}
```
### <span id="RsaEncrypt">RsaEncrypt</span>
<p>用公钥文件ras加密数据</p>
@@ -977,19 +921,18 @@ import (
)
func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
data := []byte("hello world")
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
data := []byte("hello world")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted)) //hello world
}
```
### <span id="RsaDecrypt">RsaDecrypt</span>
<p>用私钥文件rsa解密数据</p>
@@ -1011,16 +954,14 @@ import (
)
func main() {
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
data := []byte("hello world")
err := cryptor.GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem")
if err != nil {
fmt.Println(err)
}
data := []byte("hello world")
encrypted := cryptor.RsaEncrypt(data, "rsa_public.pem")
decrypted := cryptor.RsaDecrypt(encrypted, "rsa_private.pem")
fmt.Println(string(decrypted)) //hello world
fmt.Println(string(decrypted)) //hello world
}
```

View File

@@ -1,4 +1,5 @@
# Datetime
Package datetime supports date and time format and compare.
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ Package datetime supports date and time format and compare.
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/datetime"
@@ -19,65 +21,67 @@ import (
<div STYLE="page-break-after: always;"></div>
## Index
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
- [BeginOfWeek](#BeginOfWeek)
- [BeginOfMonth](#BeginOfMonth)
- [BeginOfYear](#BeginOfYear)
- [EndOfMinute](#EndOfMinute)
- [EndOfHour](#EndOfHour)
- [EndOfDay](#EndOfDay)
- [EndOfWeek](#EndOfWeek)
- [EndOfMonth](#EndOfMonth)
- [EndOfYear](#EndOfYear)
- [GetNowDate](#GetNowDate)
- [GetNowTime](#GetNowTime)
- [GetNowDateTime](#GetNowDateTime)
- [GetZeroHourTimestamp](#GetZeroHourTimestamp)
- [GetNightTimestamp](#GetNightTimestamp)
- [FormatTimeToStr](#FormatTimeToStr)
- [FormatStrToTime](#FormatStrToTime)
- [NewUnixNow](#NewUnixNow)
- [NewUnix](#NewUnix)
- [NewFormat](#NewFormat)
- [NewISO8601](#NewISO8601)
- [ToUnix](#ToUnix)
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
- [BeginOfWeek](#BeginOfWeek)
- [BeginOfMonth](#BeginOfMonth)
- [BeginOfYear](#BeginOfYear)
- [EndOfMinute](#EndOfMinute)
- [EndOfHour](#EndOfHour)
- [EndOfDay](#EndOfDay)
- [EndOfWeek](#EndOfWeek)
- [EndOfMonth](#EndOfMonth)
- [EndOfYear](#EndOfYear)
- [GetNowDate](#GetNowDate)
- [GetNowTime](#GetNowTime)
- [GetNowDateTime](#GetNowDateTime)
- [GetZeroHourTimestamp](#GetZeroHourTimestamp)
- [GetNightTimestamp](#GetNightTimestamp)
- [FormatTimeToStr](#FormatTimeToStr)
- [FormatStrToTime](#FormatStrToTime)
- [NewUnixNow](#NewUnixNow)
- [NewUnix](#NewUnix)
- [NewFormat](#NewFormat)
- [NewISO8601](#NewISO8601)
- [ToUnix](#ToUnix)
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
<div STYLE="page-break-after: always;"></div>
## Documentation
## Note:
1. 'format' string param in func FormatTimeToStr and FormatStrToTime function should be one of flows:
- yyyy-mm-dd hh:mm:ss
- yyyy-mm-dd hh:mm
- yyyy-mm-dd hh
- yyyy-mm-dd
- yyyy-mm
- mm-dd
- dd-mm-yy hh:mm:ss
- yyyy/mm/dd hh:mm:ss
- yyyy/mm/dd hh:mm
- yyyy-mm-dd hh
- yyyy/mm/dd
- yyyy/mm
- mm/dd
- dd/mm/yy hh:mm:ss
- yyyy
- mm
- hh:mm:ss
- mm:ss
1. 'format' string param in func FormatTimeToStr and FormatStrToTime function should be one of flows:
- yyyy-mm-dd hh:mm:ss
- yyyy-mm-dd hh:mm
- yyyy-mm-dd hh
- yyyy-mm-dd
- yyyy-mm
- mm-dd
- dd-mm-yy hh:mm:ss
- yyyy/mm/dd hh:mm:ss
- yyyy/mm/dd hh:mm
- yyyy-mm-dd hh
- yyyy/mm/dd
- yyyy/mm
- mm/dd
- dd/mm/yy hh:mm:ss
- yyyy
- mm
- hh:mm:ss
- mm:ss
### <span id="AddDay">AddDay</span>
<p>Add or sub days to time.</p>
<b>Signature:</b>
@@ -85,6 +89,7 @@ import (
```go
func AddDay(t time.Time, day int64) time.Time
```
<b>Example:</b>
```go
@@ -105,8 +110,8 @@ func main() {
}
```
### <span id="AddHour">AddHour</span>
<p>Add or sub hours to time.</p>
<b>Signature:</b>
@@ -114,6 +119,7 @@ func main() {
```go
func AddHour(t time.Time, hour int64) time.Time
```
<b>Example:</b>
```go
@@ -135,6 +141,7 @@ func main() {
```
### <span id="AddMinute">AddMinute</span>
<p>Add or sub minutes to time.</p>
<b>Signature:</b>
@@ -142,6 +149,7 @@ func main() {
```go
func AddMinute(t time.Time, minute int64) time.Time
```
<b>Example:</b>
```go
@@ -163,6 +171,7 @@ func main() {
```
### <span id="BeginOfMinute">BeginOfMinute</span>
<p>Return beginning minute time of day.</p>
<b>Signature:</b>
@@ -170,6 +179,7 @@ func main() {
```go
func BeginOfMinute(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -189,6 +199,7 @@ func main() {
```
### <span id="BeginOfHour">BeginOfHour</span>
<p>Return zero time of day.</p>
<b>Signature:</b>
@@ -196,6 +207,7 @@ func main() {
```go
func BeginOfHour(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -215,6 +227,7 @@ func main() {
```
### <span id="BeginOfDay">BeginOfDay</span>
<p>Return begin time of day.</p>
<b>Signature:</b>
@@ -222,6 +235,7 @@ func main() {
```go
func BeginOfDay(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -240,9 +254,8 @@ func main() {
}
```
### <span id="BeginOfWeek">BeginOfWeek</span>
<p>Return beginning time of week, week begin from Sunday.</p>
<b>Signature:</b>
@@ -250,6 +263,7 @@ func main() {
```go
func BeginOfWeek(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -268,9 +282,8 @@ func main() {
}
```
### <span id="BeginOfMonth">BeginOfMonth</span>
<p>Return beginning time of month</p>
<b>Signature:</b>
@@ -278,6 +291,7 @@ func main() {
```go
func BeginOfMonth(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -296,8 +310,8 @@ func main() {
}
```
### <span id="BeginOfYear">BeginOfYear</span>
<p>Return beginning time of year.</p>
<b>Signature:</b>
@@ -305,6 +319,7 @@ func main() {
```go
func BeginOfYear(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -323,9 +338,8 @@ func main() {
}
```
### <span id="EndOfMinute">EndOfMinute</span>
<p>Return end time minute of day.</p>
<b>Signature:</b>
@@ -333,6 +347,7 @@ func main() {
```go
func EndOfMinute(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -352,6 +367,7 @@ func main() {
```
### <span id="EndOfHour">EndOfHour</span>
<p>Return end time hour of day.</p>
<b>Signature:</b>
@@ -359,6 +375,7 @@ func main() {
```go
func EndOfHour(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -378,6 +395,7 @@ func main() {
```
### <span id="EndOfDay">EndOfDay</span>
<p>Return end time hour of day.</p>
<b>Signature:</b>
@@ -385,6 +403,7 @@ func main() {
```go
func EndOfDay(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -403,9 +422,8 @@ func main() {
}
```
### <span id="EndOfWeek">EndOfWeek</span>
<p>Return end time of week, week end with Saturday.</p>
<b>Signature:</b>
@@ -413,6 +431,7 @@ func main() {
```go
func EndOfWeek(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -431,9 +450,8 @@ func main() {
}
```
### <span id="EndOfMonth">EndOfMonth</span>
<p>Return end time of month</p>
<b>Signature:</b>
@@ -441,6 +459,7 @@ func main() {
```go
func EndOfMonth(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -459,8 +478,8 @@ func main() {
}
```
### <span id="EndOfYear">EndOfYear</span>
<p>Return beginning time of year.</p>
<b>Signature:</b>
@@ -468,6 +487,7 @@ func main() {
```go
func EndOfYear(t time.Time) time.Time
```
<b>Example:</b>
```go
@@ -486,8 +506,8 @@ func main() {
}
```
### <span id="GetNowDate">GetNowDate</span>
<p>Get current date string, format is yyyy-mm-dd.</p>
<b>Signature:</b>
@@ -495,6 +515,7 @@ func main() {
```go
func GetNowDate() string
```
<b>Example:</b>
```go
@@ -513,8 +534,8 @@ func main() {
}
```
### <span id="GetNowTime">GetNowTime</span>
<p>Get current time string, format is hh:mm:ss.</p>
<b>Signature:</b>
@@ -522,6 +543,7 @@ func main() {
```go
func GetNowTime() string
```
<b>Example:</b>
```go
@@ -540,8 +562,8 @@ func main() {
}
```
### <span id="GetNowDateTime">GetNowDateTime</span>
<p>Get current date time string, format is yyyy-mm-dd hh:mm:ss.</p>
<b>Signature:</b>
@@ -549,6 +571,7 @@ func main() {
```go
func GetNowDateTime() string
```
<b>Example:</b>
```go
@@ -567,8 +590,8 @@ func main() {
}
```
### <span id="GetZeroHourTimestamp">GetZeroHourTimestamp</span>
<p>Return timestamp of zero hour (timestamp of 00:00).</p>
<b>Signature:</b>
@@ -576,6 +599,7 @@ func main() {
```go
func GetZeroHourTimestamp() int64
```
<b>Example:</b>
```go
@@ -594,8 +618,8 @@ func main() {
}
```
### <span id="GetNightTimestamp">GetNightTimestamp</span>
<p>Return timestamp of zero hour (timestamp of 23:59).</p>
<b>Signature:</b>
@@ -603,6 +627,7 @@ func main() {
```go
func GetNightTimestamp() int64
```
<b>Example:</b>
```go
@@ -622,6 +647,7 @@ func main() {
```
### <span id="FormatTimeToStr">FormatTimeToStr</span>
<p>Format time to string, `format` param specification see note 1.</p>
<b>Signature:</b>
@@ -629,6 +655,7 @@ func main() {
```go
func FormatTimeToStr(t time.Time, format string) string
```
<b>Example:</b>
```go
@@ -647,8 +674,8 @@ func main() {
}
```
### <span id="FormatStrToTime">FormatStrToTime</span>
<p>Format string to time, `format` param specification see note 1.</p>
<b>Signature:</b>
@@ -656,6 +683,7 @@ func main() {
```go
func FormatStrToTime(str, format string) (time.Time, error)
```
<b>Example:</b>
```go
@@ -672,19 +700,19 @@ func main() {
}
```
### <span id="NewUnixNow">NewUnixNow</span>
<p>Return unix timestamp of current time</p>
<b>Signature:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewUnixNow() *theTime
```
<b>Example:</b>
```go
@@ -701,18 +729,19 @@ func main() {
}
```
### <span id="NewUnix">NewUnix</span>
<p>Return unix timestamp of specified int64 value.</p>
<b>Signature:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewUnix(unix int64) *theTime
```
<b>Example:</b>
```go
@@ -729,19 +758,19 @@ func main() {
}
```
### <span id="NewFormat">NewFormat</span>
<p>Return unix timestamp of specified time string, t should be "yyyy-mm-dd hh:mm:ss".</p>
<b>Signature:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewFormat(t string) (*theTime, error)
```
<b>Example:</b>
```go
@@ -758,20 +787,19 @@ func main() {
}
```
### <span id="NewISO8601">NewISO8601</span>
<p>Return unix timestamp of specified iso8601 time string.</p>
<b>Signature:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewISO8601(iso8601 string) (*theTime, error)
```
<b>Example:</b>
```go
@@ -788,9 +816,8 @@ func main() {
}
```
### <span id="ToUnix">ToUnix</span>
<p>Return unix timestamp.</p>
<b>Signature:</b>
@@ -798,6 +825,7 @@ func main() {
```go
func (t *theTime) ToUnix() int64
```
<b>Example:</b>
```go
@@ -814,9 +842,8 @@ func main() {
}
```
### <span id="ToFormat">ToFormat</span>
<p>Return time string 'yyyy-mm-dd hh:mm:ss'.</p>
<b>Signature:</b>
@@ -824,6 +851,7 @@ func main() {
```go
func (t *theTime) ToFormat() string
```
<b>Example:</b>
```go
@@ -840,9 +868,8 @@ func main() {
}
```
### <span id="ToFormatForTpl">ToFormatForTpl</span>
<p>Return the time string which format is specified tpl.</p>
<b>Signature:</b>
@@ -850,6 +877,7 @@ func main() {
```go
func (t *theTime) ToFormatForTpl(tpl string) string
```
<b>Example:</b>
```go
@@ -867,8 +895,8 @@ func main() {
}
```
### <span id="ToIso8601">ToIso8601</span>
<p>Return iso8601 time string.</p>
<b>Signature:</b>
@@ -876,6 +904,7 @@ func main() {
```go
func (t *theTime) ToIso8601() string
```
<b>Example:</b>
```go

View File

@@ -1,5 +1,6 @@
# Datetime
datetime日期时间处理包格式化日期比较日期。
datetime 日期时间处理包,格式化日期,比较日期。
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ datetime日期时间处理包格式化日期比较日期。
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/datetime"
@@ -19,64 +21,67 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
- [BeginOfWeek](#BeginOfWeek)
- [BeginOfMonth](#BeginOfMonth)
- [BeginOfYear](#BeginOfYear)
- [EndOfMinute](#EndOfMinute)
- [EndOfHour](#EndOfHour)
- [EndOfDay](#EndOfDay)
- [EndOfWeek](#EndOfWeek)
- [EndOfMonth](#EndOfMonth)
- [EndOfYear](#EndOfYear)
- [GetNowDate](#GetNowDate)
- [GetNowTime](#GetNowTime)
- [GetNowDateTime](#GetNowDateTime)
- [GetZeroHourTimestamp](#GetZeroHourTimestamp)
- [GetNightTimestamp](#GetNightTimestamp)
- [FormatTimeToStr](#FormatTimeToStr)
- [FormatStrToTime](#FormatStrToTime)
- [NewUnixNow](#NewUnixNow)
- [NewUnix](#NewUnix)
- [NewFormat](#NewFormat)
- [NewISO8601](#NewISO8601)
- [ToUnix](#ToUnix)
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
- [AddDay](#AddDay)
- [AddHour](#AddHour)
- [AddMinute](#AddMinute)
- [BeginOfMinute](#BeginOfMinute)
- [BeginOfHour](#BeginOfHour)
- [BeginOfDay](#BeginOfDay)
- [BeginOfWeek](#BeginOfWeek)
- [BeginOfMonth](#BeginOfMonth)
- [BeginOfYear](#BeginOfYear)
- [EndOfMinute](#EndOfMinute)
- [EndOfHour](#EndOfHour)
- [EndOfDay](#EndOfDay)
- [EndOfWeek](#EndOfWeek)
- [EndOfMonth](#EndOfMonth)
- [EndOfYear](#EndOfYear)
- [GetNowDate](#GetNowDate)
- [GetNowTime](#GetNowTime)
- [GetNowDateTime](#GetNowDateTime)
- [GetZeroHourTimestamp](#GetZeroHourTimestamp)
- [GetNightTimestamp](#GetNightTimestamp)
- [FormatTimeToStr](#FormatTimeToStr)
- [FormatStrToTime](#FormatStrToTime)
- [NewUnixNow](#NewUnixNow)
- [NewUnix](#NewUnix)
- [NewFormat](#NewFormat)
- [NewISO8601](#NewISO8601)
- [ToUnix](#ToUnix)
- [ToFormat](#ToFormat)
- [ToFormatForTpl](#ToFormatForTpl)
- [ToIso8601](#ToIso8601)
<div STYLE="page-break-after: always;"></div>
## 文档
## 注:
1. 方法FormatTimeToStr和FormatStrToTime中的format参数值需要传以下类型之一
- yyyy-mm-dd hh:mm:ss
- yyyy-mm-dd hh:mm
- yyyy-mm-dd hh
- yyyy-mm-dd
- yyyy-mm
- mm-dd
- dd-mm-yy hh:mm:ss
- yyyy/mm/dd hh:mm:ss
- yyyy/mm/dd hh:mm
- yyyy-mm-dd hh
- yyyy/mm/dd
- yyyy/mm
- mm/dd
- dd/mm/yy hh:mm:ss
- yyyy
- mm
- hh:mm:ss
- mm:ss
1. 方法 FormatTimeToStr 和 FormatStrToTime 中的 format 参数值需要传以下类型之一:
- yyyy-mm-dd hh:mm:ss
- yyyy-mm-dd hh:mm
- yyyy-mm-dd hh
- yyyy-mm-dd
- yyyy-mm
- mm-dd
- dd-mm-yy hh:mm:ss
- yyyy/mm/dd hh:mm:ss
- yyyy/mm/dd hh:mm
- yyyy-mm-dd hh
- yyyy/mm/dd
- yyyy/mm
- mm/dd
- dd/mm/yy hh:mm:ss
- yyyy
- mm
- hh:mm:ss
- mm:ss
### <span id="AddDay">AddDay</span>
<p>将日期加/减天数</p>
<b>函数签名:</b>
@@ -84,6 +89,7 @@ import (
```go
func AddDay(t time.Time, day int64) time.Time
```
<b>例子:</b>
```go
@@ -97,15 +103,15 @@ import (
func main() {
now := time.Now()
after2Days := datetime.AddDay(now, 2)
before2Days := datetime.AddDay(now, -2)
after2Days := datetime.AddDay(now, 2)
before2Days := datetime.AddDay(now, -2)
fmt.Println(after2Days, before2Days)
}
```
### <span id="AddHour">AddHour</span>
<p>将日期加/减小时数</p>
<b>函数签名:</b>
@@ -113,6 +119,7 @@ func main() {
```go
func AddHour(t time.Time, hour int64) time.Time
```
<b>例子:</b>
```go
@@ -134,6 +141,7 @@ func main() {
```
### <span id="AddMinute">AddMinute</span>
<p>将日期加/减分钟数</p>
<b>函数签名:</b>
@@ -141,6 +149,7 @@ func main() {
```go
func AddMinute(t time.Time, minute int64) time.Time
```
<b>例子:</b>
```go
@@ -162,6 +171,7 @@ func main() {
```
### <span id="BeginOfMinute">BeginOfMinute</span>
<p>返回指定时间的分钟开始时间</p>
<b>函数签名:</b>
@@ -169,6 +179,7 @@ func main() {
```go
func BeginOfMinute(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -188,6 +199,7 @@ func main() {
```
### <span id="BeginOfHour">BeginOfHour</span>
<p>返回指定时间的小时开始时间</p>
<b>函数签名:</b>
@@ -195,6 +207,7 @@ func main() {
```go
func BeginOfHour(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -214,6 +227,7 @@ func main() {
```
### <span id="BeginOfDay">BeginOfDay</span>
<p>返回指定时间的当天开始时间</p>
<b>函数签名:</b>
@@ -221,6 +235,7 @@ func main() {
```go
func BeginOfDay(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -239,9 +254,8 @@ func main() {
}
```
### <span id="BeginOfWeek">BeginOfWeek</span>
<p>返回指定时间的星期开始时间</p>
<b>函数签名:</b>
@@ -249,6 +263,7 @@ func main() {
```go
func BeginOfWeek(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -267,9 +282,8 @@ func main() {
}
```
### <span id="BeginOfMonth">BeginOfMonth</span>
<p>返回指定时间的当月开始时间</p>
<b>函数签名:</b>
@@ -277,6 +291,7 @@ func main() {
```go
func BeginOfMonth(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -295,8 +310,8 @@ func main() {
}
```
### <span id="BeginOfYear">BeginOfYear</span>
<p>返回指定时间的当年开始时间</p>
<b>函数签名:</b>
@@ -304,6 +319,7 @@ func main() {
```go
func BeginOfYear(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -322,9 +338,8 @@ func main() {
}
```
### <span id="EndOfMinute">EndOfMinute</span>
<p>返回指定时间的分钟结束时间</p>
<b>函数签名:</b>
@@ -332,6 +347,7 @@ func main() {
```go
func EndOfMinute(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -351,6 +367,7 @@ func main() {
```
### <span id="EndOfHour">EndOfHour</span>
<p>返回指定时间的小时结束时间</p>
<b>函数签名:</b>
@@ -358,6 +375,7 @@ func main() {
```go
func EndOfHour(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -377,6 +395,7 @@ func main() {
```
### <span id="EndOfDay">EndOfDay</span>
<p>返回指定时间的当天结束时间.</p>
<b>函数签名:</b>
@@ -384,6 +403,7 @@ func main() {
```go
func EndOfDay(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -402,9 +422,8 @@ func main() {
}
```
### <span id="EndOfWeek">EndOfWeek</span>
<p>返回指定时间的星期结束时间</p>
<b>函数签名:</b>
@@ -412,6 +431,7 @@ func main() {
```go
func EndOfWeek(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -430,9 +450,8 @@ func main() {
}
```
### <span id="EndOfMonth">EndOfMonth</span>
<p>返回指定时间的月份结束时间</p>
<b>函数签名:</b>
@@ -440,6 +459,7 @@ func main() {
```go
func EndOfMonth(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -458,8 +478,8 @@ func main() {
}
```
### <span id="EndOfYear">EndOfYear</span>
<p>返回指定时间的年份结束时间</p>
<b>函数签名:</b>
@@ -467,6 +487,7 @@ func main() {
```go
func EndOfYear(t time.Time) time.Time
```
<b>例子:</b>
```go
@@ -485,8 +506,8 @@ func main() {
}
```
### <span id="GetNowDate">GetNowDate</span>
<p>获取当天日期返回格式yyyy-mm-dd</p>
<b>函数签名:</b>
@@ -494,6 +515,7 @@ func main() {
```go
func GetNowDate() string
```
<b>例子:</b>
```go
@@ -507,13 +529,13 @@ import (
func main() {
now := time.Now()
currentDate := datetime.GetNowDate()
currentDate := datetime.GetNowDate()
fmt.Println(currentDate) // 2022-01-28
}
```
### <span id="GetNowTime">GetNowTime</span>
<p>获取当时时间返回格式hh:mm:ss</p>
<b>函数签名:</b>
@@ -521,6 +543,7 @@ func main() {
```go
func GetNowTime() string
```
<b>例子:</b>
```go
@@ -539,8 +562,8 @@ func main() {
}
```
### <span id="GetNowDateTime">GetNowDateTime</span>
<p>获取当时日期和时间返回格式yyyy-mm-dd hh:mm:ss.</p>
<b>函数签名:</b>
@@ -548,6 +571,7 @@ func main() {
```go
func GetNowDateTime() string
```
<b>例子:</b>
```go
@@ -566,8 +590,8 @@ func main() {
}
```
### <span id="GetZeroHourTimestamp">GetZeroHourTimestamp</span>
<p>获取零时时间戳(timestamp of 00:00).</p>
<b>函数签名:</b>
@@ -575,6 +599,7 @@ func main() {
```go
func GetZeroHourTimestamp() int64
```
<b>例子:</b>
```go
@@ -593,8 +618,8 @@ func main() {
}
```
### <span id="GetNightTimestamp">GetNightTimestamp</span>
<p>获取午夜时间戳(timestamp of 23:59).</p>
<b>函数签名:</b>
@@ -602,6 +627,7 @@ func main() {
```go
func GetNightTimestamp() int64
```
<b>例子:</b>
```go
@@ -621,6 +647,7 @@ func main() {
```
### <span id="FormatTimeToStr">FormatTimeToStr</span>
<p>将日期格式化成字符串,`format` 参数格式参考注<sup>1</sup></p>
<b>函数签名:</b>
@@ -628,6 +655,7 @@ func main() {
```go
func FormatTimeToStr(t time.Time, format string) string
```
<b>例子:</b>
```go
@@ -646,8 +674,8 @@ func main() {
}
```
### <span id="FormatStrToTime">FormatStrToTime</span>
<p>将字符串格式化成时间,`format` 参数格式参考注<sup>1</sup></p>
<b>函数签名:</b>
@@ -655,6 +683,7 @@ func main() {
```go
func FormatStrToTime(str, format string) (time.Time, error)
```
<b>例子:</b>
```go
@@ -671,19 +700,19 @@ func main() {
}
```
### <span id="NewUnixNow">NewUnixNow</span>
<p>创建一个当前时间的unix时间戳</p>
<b>函数签名:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewUnixNow() *theTime
```
<b>例子:</b>
```go
@@ -700,18 +729,19 @@ func main() {
}
```
### <span id="NewUnix">NewUnix</span>
<p>创建一个unix时间戳</p>
<b>函数签名:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewUnix(unix int64) *theTime
```
<b>例子:</b>
```go
@@ -728,19 +758,19 @@ func main() {
}
```
### <span id="NewFormat">NewFormat</span>
<p>创建一个yyyy-mm-dd hh:mm:ss格式时间字符串的unix时间戳</p>
<b>函数签名:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewFormat(t string) (*theTime, error)
```
<b>例子:</b>
```go
@@ -757,20 +787,19 @@ func main() {
}
```
### <span id="NewISO8601">NewISO8601</span>
<p>创建一个iso8601格式时间字符串的unix时间戳</p>
<b>函数签名:</b>
```go
type theTime struct {
unix int64
unix int64
}
func NewISO8601(iso8601 string) (*theTime, error)
```
<b>例子:</b>
```go
@@ -787,9 +816,8 @@ func main() {
}
```
### <span id="ToUnix">ToUnix</span>
<p>返回unix时间戳</p>
<b>函数签名:</b>
@@ -797,6 +825,7 @@ func main() {
```go
func (t *theTime) ToUnix() int64
```
<b>例子:</b>
```go
@@ -813,9 +842,8 @@ func main() {
}
```
### <span id="ToFormat">ToFormat</span>
<p>返回格式'yyyy-mm-dd hh:mm:ss'的日期字符串</p>
<b>函数签名:</b>
@@ -823,6 +851,7 @@ func main() {
```go
func (t *theTime) ToFormat() string
```
<b>例子:</b>
```go
@@ -839,9 +868,8 @@ func main() {
}
```
### <span id="ToFormatForTpl">ToFormatForTpl</span>
<p>返回tpl格式指定的日期字符串</p>
<b>函数签名:</b>
@@ -849,6 +877,7 @@ func main() {
```go
func (t *theTime) ToFormatForTpl(tpl string) string
```
<b>例子:</b>
```go
@@ -866,8 +895,8 @@ func main() {
}
```
### <span id="ToIso8601">ToIso8601</span>
<p>返回iso8601日期字符串</p>
<b>函数签名:</b>
@@ -875,6 +904,7 @@ func main() {
```go
func (t *theTime) ToIso8601() string
```
<b>例子:</b>
```go
@@ -891,4 +921,3 @@ func main() {
fmt.Println(ts) //"2006-01-02T23:04:05+08:00"
}
```

View File

@@ -1,4 +1,5 @@
# Fileutil
Package fileutil implements some basic functions for file operations.
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ Package fileutil implements some basic functions for file operations.
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/fileutil"
@@ -19,29 +21,29 @@ import (
<div STYLE="page-break-after: always;"></div>
## Index
- [ClearFile](#ClearFile)
- [CreateFile](#CreateFile)
- [CreateDir](#CreateDir)
- [CopyFile](#CopyFile)
- [FileMode](#FileMode)
- [MiMeType](#MiMeType)
- [IsExist](#IsExist)
- [IsLink](#IsLink)
- [IsDir](#IsDir)
- [ListFileNames](#ListFileNames)
- [RemoveFile](#RemoveFile)
- [ReadFileToString](#ReadFileToString)
- [ReadFileByLine](#ReadFileByLine)
- [Zip](#Zip)
- [UnZip](#UnZip)
- [ClearFile](#ClearFile)
- [CreateFile](#CreateFile)
- [CreateDir](#CreateDir)
- [CopyFile](#CopyFile)
- [FileMode](#FileMode)
- [MiMeType](#MiMeType)
- [IsExist](#IsExist)
- [IsLink](#IsLink)
- [IsDir](#IsDir)
- [ListFileNames](#ListFileNames)
- [RemoveFile](#RemoveFile)
- [ReadFileToString](#ReadFileToString)
- [ReadFileByLine](#ReadFileByLine)
- [Zip](#Zip)
- [UnZip](#UnZip)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="ClearFile">ClearFile</span>
<p>Clear the file content, write empty string to the file.</p>
<b>Signature:</b>
@@ -49,6 +51,7 @@ import (
```go
func ClearFile(path string) error
```
<b>Example:</b>
```go
@@ -67,9 +70,8 @@ func main() {
}
```
### <span id="CreateDir">CreateDir</span>
<p>Create directory in absolute path. param `absPath` like /a/, /a/b/.</p>
<b>Signature:</b>
@@ -77,6 +79,7 @@ func main() {
```go
func CreateDir(absPath string) error
```
<b>Example:</b>
```go
@@ -93,9 +96,8 @@ func main() {
}
```
### <span id="CreateFile">CreateFile</span>
<p>Create file in path. return true if create succeed.</p>
<b>Signature:</b>
@@ -103,6 +105,7 @@ func main() {
```go
func CreateFile(path string) bool
```
<b>Example:</b>
```go
@@ -119,8 +122,8 @@ func main() {
}
```
### <span id="CopyFile">CopyFile</span>
<p>Copy src file to dest file. If dest file exist will overwrite it.</p>
<b>Signature:</b>
@@ -128,6 +131,7 @@ func main() {
```go
func CopyFile(srcFilePath string, dstFilePath string) error
```
<b>Example:</b>
```go
@@ -140,15 +144,14 @@ import (
func main() {
err := fileutil.CopyFile("./test.txt", "./test_copy.txt")
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
}
```
### <span id="FileMode">FileMode</span>
<p>Return file mode infomation.</p>
<b>Signature:</b>
@@ -156,6 +159,7 @@ func main() {
```go
func FileMode(path string) (fs.FileMode, error)
```
<b>Example:</b>
```go
@@ -168,16 +172,15 @@ import (
func main() {
mode, err := fileutil.FileMode("./test.txt")
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
fmt.Println(mode)
}
```
### <span id="MiMeType">MiMeType</span>
<p>Get file mime type, 'file' param's type should be string or *os.File.</p>
<b>Signature:</b>
@@ -185,6 +188,7 @@ func main() {
```go
func MiMeType(file interface{}) string
```
<b>Example:</b>
```go
@@ -206,10 +210,8 @@ func main() {
}
```
### <span id="IsExist">IsExist</span>
<p>Checks if a file or directory exists.</p>
<b>Signature:</b>
@@ -217,6 +219,7 @@ func main() {
```go
func IsExist(path string) bool
```
<b>Example:</b>
```go
@@ -234,9 +237,8 @@ func main() {
}
```
### <span id="IsLink">IsLink</span>
<p>Checks if a file is symbol link or not.</p>
<b>Signature:</b>
@@ -244,6 +246,7 @@ func main() {
```go
func IsLink(path string) bool
```
<b>Example:</b>
```go
@@ -260,16 +263,16 @@ func main() {
}
```
### <span id="IsDir">IsDir</span>
<p>Checks if the path is directy or not.</p>
<b>Signature:</b>
```go
func IsDir(path string) bool
func IsDir(path string) bool
```
<b>Example:</b>
```go
@@ -289,9 +292,8 @@ func main() {
}
```
### <span id="ListFileNames">ListFileNames</span>
<p>List all file names in given path.</p>
<b>Signature:</b>
@@ -299,6 +301,7 @@ func main() {
```go
func ListFileNames(path string) ([]string, error)
```
<b>Example:</b>
```go
@@ -315,9 +318,8 @@ func main() {
}
```
### <span id="RemoveFile">RemoveFile</span>
<p>Remove the file of path.</p>
<b>Signature:</b>
@@ -325,6 +327,7 @@ func main() {
```go
func RemoveFile(path string) error
```
<b>Example:</b>
```go
@@ -338,13 +341,13 @@ import (
func main() {
err := fileutil.RemoveFile("./test.txt")
if err != nil {
fmt.Println(err)
}
fmt.Println(err)
}
}
```
### <span id="ReadFileToString">ReadFileToString</span>
<p>Return string of file content.</p>
<b>Signature:</b>
@@ -352,6 +355,7 @@ func main() {
```go
func ReadFileToString(path string) (string, error)
```
<b>Example:</b>
```go
@@ -365,19 +369,18 @@ import (
func main() {
path := "./test.txt"
fileutil.CreateFile(path)
fileutil.CreateFile(path)
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
f.WriteString("hello world")
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
f.WriteString("hello world")
content, _ := fileutil.ReadFileToString(path)
content, _ := fileutil.ReadFileToString(path)
fmt.Println(content) //hello world
}
```
### <span id="ReadFileByLine">ReadFileByLine</span>
<p>Read file line by line, and return slice of lines</p>
<b>Signature:</b>
@@ -385,6 +388,7 @@ func main() {
```go
func ReadFileByLine(path string)([]string, error)
```
<b>Example:</b>
```go
@@ -398,20 +402,19 @@ import (
func main() {
path := "./text.txt"
fileutil.CreateFile(path)
fileutil.CreateFile(path)
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close()
f.WriteString("hello\nworld")
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close()
f.WriteString("hello\nworld")
contents, _ := fileutil.ReadFileByLine(path)
contents, _ := fileutil.ReadFileByLine(path)
fmt.Println(contents) //[]string{"hello", "world"}
}
```
### <span id="Zip">Zip</span>
<p>Create a zip file of fpath, fpath could be a file or a directory.</p>
<b>Signature:</b>
@@ -419,6 +422,7 @@ func main() {
```go
func Zip(fpath string, destPath string) error
```
<b>Example:</b>
```go
@@ -430,17 +434,15 @@ import (
)
func main() {
err := fileutil.Zip("./test.txt", "./test.zip")
err := fileutil.Zip("./test.txt", "./test.zip")
if err != nil {
fmt.Println(err)
}
}
```
### <span id="UnZip">UnZip</span>
<p>Unzip the file and save it to dest path.</p>
<b>Signature:</b>
@@ -448,6 +450,7 @@ func main() {
```go
func UnZip(zipFile string, destPath string) error
```
<b>Example:</b>
```go
@@ -459,14 +462,9 @@ import (
)
func main() {
err := fileutil.Zip("./test.zip", "./unzip/test.txt")
err := fileutil.Zip("./test.zip", "./unzip/test.txt")
if err != nil {
fmt.Println(err)
}
}
```

View File

@@ -1,5 +1,6 @@
# Fileutil
fileutil包支持文件基本操作。
fileutil 包支持文件基本操作。
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ fileutil包支持文件基本操作。
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/fileutil"
@@ -19,29 +21,29 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [ClearFile](#ClearFile)
- [CreateFile](#CreateFile)
- [CreateDir](#CreateDir)
- [CopyFile](#CopyFile)
- [FileMode](#FileMode)
- [MiMeType](#MiMeType)
- [IsExist](#IsExist)
- [IsLink](#IsLink)
- [IsDir](#IsDir)
- [ListFileNames](#ListFileNames)
- [RemoveFile](#RemoveFile)
- [ReadFileToString](#ReadFileToString)
- [ReadFileByLine](#ReadFileByLine)
- [Zip](#Zip)
- [UnZip](#UnZip)
- [ClearFile](#ClearFile)
- [CreateFile](#CreateFile)
- [CreateDir](#CreateDir)
- [CopyFile](#CopyFile)
- [FileMode](#FileMode)
- [MiMeType](#MiMeType)
- [IsExist](#IsExist)
- [IsLink](#IsLink)
- [IsDir](#IsDir)
- [ListFileNames](#ListFileNames)
- [RemoveFile](#RemoveFile)
- [ReadFileToString](#ReadFileToString)
- [ReadFileByLine](#ReadFileByLine)
- [Zip](#Zip)
- [UnZip](#UnZip)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="ClearFile">ClearFile</span>
<p>清空文件内容</p>
<b>函数签名:</b>
@@ -49,6 +51,7 @@ import (
```go
func ClearFile(path string) error
```
<b>例子:</b>
```go
@@ -67,8 +70,8 @@ func main() {
}
```
### <span id="CreateDir">CreateDir</span>
<p>使用绝对路径创建嵌套目录,例如/a/, /a/b/</p>
<b>函数签名:</b>
@@ -76,6 +79,7 @@ func main() {
```go
func CreateDir(absPath string) error
```
<b>例子:</b>
```go
@@ -92,9 +96,8 @@ func main() {
}
```
### <span id="CreateFile">CreateFile</span>
<p>创建文件创建成功返回true, 否则返回false</p>
<b>函数签名:</b>
@@ -102,6 +105,7 @@ func main() {
```go
func CreateFile(path string) bool
```
<b>例子:</b>
```go
@@ -118,8 +122,8 @@ func main() {
}
```
### <span id="CopyFile">CopyFile</span>
<p>拷贝文件,会覆盖原有的拷贝文件</p>
<b>函数签名:</b>
@@ -127,6 +131,7 @@ func main() {
```go
func CopyFile(srcFilePath string, dstFilePath string) error
```
<b>例子:</b>
```go
@@ -139,15 +144,14 @@ import (
func main() {
err := fileutil.CopyFile("./test.txt", "./test_copy.txt")
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
}
```
### <span id="FileMode">FileMode</span>
<p>获取文件mode信息</p>
<b>函数签名:</b>
@@ -155,6 +159,7 @@ func main() {
```go
func FileMode(path string) (fs.FileMode, error)
```
<b>例子:</b>
```go
@@ -167,16 +172,15 @@ import (
func main() {
mode, err := fileutil.FileMode("./test.txt")
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
fmt.Println(mode)
}
```
### <span id="MiMeType">MiMeType</span>
<p>获取文件mime类型, 'file'参数的类型必须是string或者*os.File</p>
<b>函数签名:</b>
@@ -184,6 +188,7 @@ func main() {
```go
func MiMeType(file interface{}) string
```
<b>例子:</b>
```go
@@ -205,10 +210,8 @@ func main() {
}
```
### <span id="IsExist">IsExist</span>
<p>判断文件或目录是否存在</p>
<b>函数签名:</b>
@@ -216,6 +219,7 @@ func main() {
```go
func IsExist(path string) bool
```
<b>例子:</b>
```go
@@ -233,9 +237,8 @@ func main() {
}
```
### <span id="IsLink">IsLink</span>
<p>判断文件是否是符号链接</p>
<b>函数签名:</b>
@@ -243,6 +246,7 @@ func main() {
```go
func IsLink(path string) bool
```
<b>例子:</b>
```go
@@ -259,16 +263,16 @@ func main() {
}
```
### <span id="IsDir">IsDir</span>
<p>判断目录是否存在</p>
<b>函数签名:</b>
```go
func IsDir(path string) bool
func IsDir(path string) bool
```
<b>例子:</b>
```go
@@ -288,9 +292,8 @@ func main() {
}
```
### <span id="ListFileNames">ListFileNames</span>
<p>返回目录下所有文件名</p>
<b>函数签名:</b>
@@ -298,6 +301,7 @@ func main() {
```go
func ListFileNames(path string) ([]string, error)
```
<b>例子:</b>
```go
@@ -314,9 +318,8 @@ func main() {
}
```
### <span id="RemoveFile">RemoveFile</span>
<p>删除文件</p>
<b>函数签名:</b>
@@ -324,6 +327,7 @@ func main() {
```go
func RemoveFile(path string) error
```
<b>例子:</b>
```go
@@ -337,13 +341,13 @@ import (
func main() {
err := fileutil.RemoveFile("./test.txt")
if err != nil {
fmt.Println(err)
}
fmt.Println(err)
}
}
```
### <span id="ReadFileToString">ReadFileToString</span>
<p>读取文件内容并返回字符串</p>
<b>函数签名:</b>
@@ -351,6 +355,7 @@ func main() {
```go
func ReadFileToString(path string) (string, error)
```
<b>例子:</b>
```go
@@ -364,19 +369,18 @@ import (
func main() {
path := "./test.txt"
fileutil.CreateFile(path)
fileutil.CreateFile(path)
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
f.WriteString("hello world")
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
f.WriteString("hello world")
content, _ := fileutil.ReadFileToString(path)
content, _ := fileutil.ReadFileToString(path)
fmt.Println(content) //hello world
}
```
### <span id="ReadFileByLine">ReadFileByLine</span>
<p>按行读取文件内容,返回字符串切片包含每一行</p>
<b>函数签名:</b>
@@ -384,6 +388,7 @@ func main() {
```go
func ReadFileByLine(path string)([]string, error)
```
<b>例子:</b>
```go
@@ -397,20 +402,19 @@ import (
func main() {
path := "./text.txt"
fileutil.CreateFile(path)
fileutil.CreateFile(path)
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close()
f.WriteString("hello\nworld")
f, _ := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0777)
defer f.Close()
f.WriteString("hello\nworld")
contents, _ := fileutil.ReadFileByLine(path)
contents, _ := fileutil.ReadFileByLine(path)
fmt.Println(contents) //[]string{"hello", "world"}
}
```
### <span id="Zip">Zip</span>
<p>zip压缩文件, fpath参数可以是文件或目录</p>
<b>函数签名:</b>
@@ -418,6 +422,7 @@ func main() {
```go
func Zip(fpath string, destPath string) error
```
<b>例子:</b>
```go
@@ -429,17 +434,15 @@ import (
)
func main() {
err := fileutil.Zip("./test.txt", "./test.zip")
err := fileutil.Zip("./test.txt", "./test.zip")
if err != nil {
fmt.Println(err)
}
}
```
### <span id="UnZip">UnZip</span>
<p>zip解压缩文件并保存在目录中</p>
<b>Signature:</b>
@@ -447,6 +450,7 @@ func main() {
```go
func UnZip(zipFile string, destPath string) error
```
<b>例子:</b>
```go
@@ -458,14 +462,9 @@ import (
)
func main() {
err := fileutil.Zip("./test.zip", "./unzip/test.txt")
err := fileutil.Zip("./test.zip", "./unzip/test.txt")
if err != nil {
fmt.Println(err)
}
}
```

View File

@@ -1,4 +1,5 @@
# Formatter
formatter contains some functions for data formatting.
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ formatter contains some functions for data formatting.
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/formatter"
@@ -19,15 +21,15 @@ import (
<div STYLE="page-break-after: always;"></div>
## Index
- [Comma](#Comma)
- [Comma](#Comma)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Comma">Comma</span>
<p>Add comma to number by every 3 numbers from right. ahead by symbol char.
Param should be number or numberic string.</p>
@@ -36,6 +38,7 @@ Param should be number or numberic string.</p>
```go
func Comma(v interface{}, symbol string) string
```
<b>Example:</b>
```go

View File

@@ -1,5 +1,6 @@
# Formatter
formatter格式化器包含一些数据格式化处理方法。
formatter 格式化器包含一些数据格式化处理方法。
<div STYLE="page-break-after: always;"></div>
@@ -10,6 +11,7 @@ formatter格式化器包含一些数据格式化处理方法。
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/formatter"
@@ -19,15 +21,15 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [Comma](#Comma)
- [Comma](#Comma)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="Comma">Comma</span>
<p>用逗号每隔3位分割数字/字符串,签名添加符号。参数必须是数字或者可以转为数字的字符串</p>
<b>函数签名:</b>
@@ -35,6 +37,7 @@ import (
```go
func Comma(v interface{}, symbol string) string
```
<b>例子:</b>
```go

View File

@@ -1,4 +1,5 @@
# Function
Package function can control the flow of function execution and support part of functional programming.
<div STYLE="page-break-after: always;"></div>
@@ -11,6 +12,7 @@ Package function can control the flow of function execution and support part of
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/function"
@@ -20,21 +22,21 @@ import (
<div STYLE="page-break-after: always;"></div>
## 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)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="After">After</span>
<p>Creates a function that invokes given func once it's called n or more times.</p>
<b>Signature:</b>
@@ -42,6 +44,7 @@ import (
```go
func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value
```
<b>Example:</b>
```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
}
```
### <span id="Before">Before</span>
<p>creates a function that invokes func once it's called less than n times.</p>
@@ -89,6 +90,7 @@ func main() {
```go
func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value
```
<b>Example:</b>
```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)
}
```
### <span id="Curry">Curry</span>
<p>Make a curry function.</p>
@@ -136,6 +136,7 @@ func main() {
type Fn func(...interface{}) interface{}
func (f Fn) Curry(i interface{}) func(...interface{}) interface{}
```
<b>Example:</b>
```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
}
```
### <span id="Compose">Compose</span>
<p>Compose the function list from right to left, then return the composed function.</p>
@@ -170,6 +169,7 @@ func main() {
```go
func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{}
```
<b>Example:</b>
```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
}
```
### <span id="Debounced">Debounced</span>
<p>Creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.</p>
@@ -206,6 +204,7 @@ func main() {
```go
func Debounced(fn func(), duration time.Duration) func()
```
<b>Example:</b>
```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
}
```
### <span id="Delay">Delay</span>
<p>Invoke function after delayed time.</p>
@@ -248,6 +245,7 @@ func main() {
```go
func Delay(delay time.Duration, fn interface{}, args ...interface{})
```
<b>Example:</b>
```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")
}
```
### <span id="Schedule">Schedule</span>
<p>Invoke function every duration time, until close the returned bool chan.</p>
@@ -277,6 +273,7 @@ func main() {
```go
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool
```
<b>Example:</b>
```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) //[* * * * *]
}
```
### <span id="Watcher">Watcher</span>
<p>Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.</p>
@@ -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
```
<b>Example:</b>
```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))
}
}
```

View File

@@ -1,5 +1,6 @@
# Function
function函数包控制函数执行流程包含部分函数式编程。
function 函数包控制函数执行流程,包含部分函数式编程。
<div STYLE="page-break-after: always;"></div>
@@ -11,6 +12,7 @@ function函数包控制函数执行流程包含部分函数式编程。
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/function"
@@ -20,21 +22,21 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [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)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="After">After</span>
<p>创建一个函数当他被调用n或更多次之后将马上触发fn</p>
<b>函数签名:</b>
@@ -42,6 +44,7 @@ import (
```go
func After(n int, fn interface{}) func(args ...interface{}) []reflect.Value
```
<b>例子:</b>
```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
}
```
### <span id="Before">Before</span>
<p>创建一个函数调用次数不超过n次之后再调用这个函数将返回一次最后调用fn的结果</p>
@@ -89,6 +90,7 @@ func main() {
```go
func Before(n int, fn interface{}) func(args ...interface{}) []reflect.Value
```
<b>例子:</b>
```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)
}
```
### <span id="Curry">Curry</span>
<p>创建一个柯里化的函数</p>
@@ -136,6 +136,7 @@ func main() {
type Fn func(...interface{}) interface{}
func (f Fn) Curry(i interface{}) func(...interface{}) interface{}
```
<b>例子:</b>
```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
}
```
### <span id="Compose">Compose</span>
<p>从右至左组合函数列表fnList 返回组合后的函数</p>
@@ -170,6 +169,7 @@ func main() {
```go
func Compose(fnList ...func(...interface{}) interface{}) func(...interface{}) interface{}
```
<b>例子:</b>
```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
}
```
### <span id="Debounced">Debounced</span>
<p>创建一个 debounced 函数,该函数延迟调用 fn 直到自上次调用 debounced 函数后等待持续时间过去。</p>
@@ -206,6 +204,7 @@ func main() {
```go
func Debounced(fn func(), duration time.Duration) func()
```
<b>例子:</b>
```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
}
```
### <span id="Delay">Delay</span>
<p>延迟delay时间后调用函数</p>
@@ -248,6 +245,7 @@ func main() {
```go
func Delay(delay time.Duration, fn interface{}, args ...interface{})
```
<b>例子:</b>
```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")
}
```
### <span id="Schedule">Schedule</span>
<p>每次持续时间调用函数,直到关闭返回的 bool chan</p>
@@ -277,6 +273,7 @@ func main() {
```go
func Schedule(d time.Duration, fn interface{}, args ...interface{}) chan bool
```
<b>例子:</b>
```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) //[* * * * *]
}
```
### <span id="Watcher">Watcher</span>
<p>Watcher 用于记录代码执行时间。可以启动/停止/重置手表定时器。获取函数执行的时间。 </p>
@@ -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
```
<b>例子:</b>
```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))
}
}
```

View File

@@ -1,4 +1,5 @@
# Mathutil
Package mathutil implements some functions for math calculation.
<div STYLE="page-break-after: always;"></div>
@@ -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)
<div STYLE="page-break-after: always;"></div>
## Example:
```go
import (
"github.com/duke-git/lancet/mathutil"
@@ -20,20 +21,21 @@ import (
<div STYLE="page-break-after: always;"></div>
## 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)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Exponent">Exponent</span>
<p>Calculate x to the nth power.</p>
<b>Signature:</b>
@@ -41,6 +43,7 @@ import (
```go
func Exponent(x, n int64) int64
```
<b>Example:</b>
```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
}
```
### <span id="Fibonacci">Fibonacci</span>
<p>Calculate the nth number of fibonacci sequence.</p>
<b>Signature:</b>
@@ -68,6 +70,7 @@ func main() {
```go
func Fibonacci(first, second, n int) int
```
<b>Example:</b>
```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
}
```
### <span id="Factorial">Factorial</span>
<p>Calculate the factorial of x.</p>
<b>Signature:</b>
@@ -97,6 +99,7 @@ func main() {
```go
func Factorial(x uint) uint
```
<b>Example:</b>
```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
}
```
### <span id="Percent">Percent</span>
<p>calculate the percentage of val to total, retain n decimal places.</p>
<b>Signature:</b>
@@ -125,6 +127,7 @@ func main() {
```go
func Percent(val, total float64, n int) float64
```
<b>Example:</b>
```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
}
```
### <span id="RoundToFloat">RoundToFloat</span>
<p>Round float up to n decimal places.</p>
<b>Signature:</b>
@@ -151,6 +153,7 @@ func main() {
```go
func RoundToFloat(x float64, n int) float64
```
<b>Example:</b>
```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
}
```
### <span id="RoundToString">RoundToString</span>
<p>Round float up to n decimal places. will return string.</p>
<b>Signature:</b>
@@ -181,6 +182,7 @@ func main() {
```go
func RoundToString(x float64, n int) string
```
<b>Example:</b>
```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"
}
```
### <span id="TruncRound">TruncRound</span>
<p>Round float off n decimal places.</p>
<b>Signature:</b>
@@ -210,6 +211,7 @@ func main() {
```go
func TruncRound(x float64, n int) float64
```
<b>Example:</b>
```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
}
```

View File

@@ -1,5 +1,6 @@
# Mathutil
mathutil包实现了一些数学计算的函数.
mathutil 包实现了一些数学计算的函数.
<div STYLE="page-break-after: always;"></div>
@@ -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)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/mathutil"
@@ -20,21 +21,22 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [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)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Exponent">Exponent</span>
<p>指数计算x的n次方</p>
<b>函数签名:</b>
@@ -42,6 +44,7 @@ import (
```go
func Exponent(x, n int64) int64
```
<b>例子:</b>
```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
}
```
### <span id="Fibonacci">Fibonacci</span>
<p>计算斐波那契数列的第n个数</p>
<b>函数签名:</b>
@@ -69,6 +71,7 @@ func main() {
```go
func Fibonacci(first, second, n int) int
```
<b>例子:</b>
```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
}
```
### <span id="Factorial">Factorial</span>
<p>计算阶乘</p>
<b>函数签名:</b>
@@ -98,6 +100,7 @@ func main() {
```go
func Factorial(x uint) uint
```
<b>例子:</b>
```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
}
```
### <span id="Percent">Percent</span>
<p>计算百分比保留n位小数</p>
<b>函数签名:</b>
@@ -126,6 +128,7 @@ func main() {
```go
func Percent(val, total float64, n int) float64
```
<b>例子:</b>
```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
}
```
### <span id="RoundToFloat">RoundToFloat</span>
<p>四舍五入保留n位小数</p>
<b>函数签名:</b>
@@ -152,6 +154,7 @@ func main() {
```go
func RoundToFloat(x float64, n int) float64
```
<b>例子:</b>
```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
}
```
### <span id="RoundToString">RoundToString</span>
<p>四舍五入保留n位小数返回字符串</p>
<b>函数签名:</b>
@@ -182,6 +183,7 @@ func main() {
```go
func RoundToString(x float64, n int) string
```
<b>例子:</b>
```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"
}
```
### <span id="TruncRound">TruncRound</span>
<p>截短n位小数不进行四舍五入</p>
<b>函数签名:</b>
@@ -211,6 +212,7 @@ func main() {
```go
func TruncRound(x float64, n int) float64
```
<b>例子:</b>
```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
}
```

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -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)
}
```

View File

@@ -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)
}
```

View File

@@ -1,4 +1,5 @@
# Retry
Package retry is for executing a function repeatedly until it was successful or canceled by the context.
<div STYLE="page-break-after: always;"></div>
@@ -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)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/retry"
@@ -20,18 +21,19 @@ import (
<div STYLE="page-break-after: always;"></div>
## Index
- [Context](#Context)
- [Retry](#Retry)
- [RetryFunc](#RetryFunc)
- [RetryDuration](#RetryDuration)
- [RetryTimes](#RetryTimes)
- [Context](#Context)
- [Retry](#Retry)
- [RetryFunc](#RetryFunc)
- [RetryDuration](#RetryDuration)
- [RetryTimes](#RetryTimes)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="Context">Context</span>
<p>Set retry context config, can cancel the retry with context.</p>
<b>Signature:</b>
@@ -39,43 +41,42 @@ import (
```go
func Context(ctx context.Context)
```
<b>Example:</b>
```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
}
}
```
### <span id="RetryFunc">RetryFunc</span>
<p>Function that retry executes.</p>
<b>Signature:</b>
@@ -83,6 +84,7 @@ func main() {
```go
type RetryFunc func() error
```
<b>Example:</b>
```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
}
```
### <span id="RetryTimes">RetryTimes</span>
<p>Set times of retry. Default times is 5.</p>
<b>Signature:</b>
@@ -125,6 +126,7 @@ func main() {
```go
func RetryTimes(n uint)
```
<b>Example:</b>
```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
}
}
```
### <span id="RetryDuration">RetryDuration</span>
<p>Set duration of retries. Default duration is 3 second.</p>
<b>Signature:</b>
@@ -164,6 +165,7 @@ func main() {
```go
func RetryDuration(d time.Duration)
```
<b>Example:</b>
```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
}
```
### <span id="Retry">Retry</span>
<p>Executes the retryFunc repeatedly until it was successful or canceled by the context.</p>
<b>Signature:</b>
@@ -204,6 +206,7 @@ func main() {
```go
func Retry(retryFunc RetryFunc, opts ...Option) error
```
<b>Example:</b>
```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
}

View File

@@ -1,5 +1,6 @@
# Retry
retry重试执行函数直到函数运行成功或被context cancel。
retry 重试执行函数直到函数运行成功或被 context cancel。
<div STYLE="page-break-after: always;"></div>
@@ -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)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/retry"
@@ -20,20 +21,19 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [Context](#Context)
- [Retry](#Retry)
- [RetryFunc](#RetryFunc)
- [RetryDuration](#RetryDuration)
- [RetryTimes](#RetryTimes)
- [Context](#Context)
- [Retry](#Retry)
- [RetryFunc](#RetryFunc)
- [RetryDuration](#RetryDuration)
- [RetryTimes](#RetryTimes)
<div STYLE="page-break-after: always;"></div>
## Document文档
## Document 文档
### <span id="Context">Context</span>
<p>设置重试context参数</p>
<b>函数签名:</b>
@@ -41,43 +41,42 @@ import (
```go
func Context(ctx context.Context)
```
<b>例子:</b>
```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
}
}
```
### <span id="RetryFunc">RetryFunc</span>
<p>被重试执行的函数</p>
<b>函数签名:</b>
@@ -85,6 +84,7 @@ func main() {
```go
type RetryFunc func() error
```
<b>例子:</b>
```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
}
```
### <span id="RetryTimes">RetryTimes</span>
<p>设置重试次数默认5</p>
<b>函数签名:</b>
@@ -127,6 +126,7 @@ func main() {
```go
func RetryTimes(n uint)
```
<b>例子:</b>
```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
}
}
```
### <span id="RetryDuration">RetryDuration</span>
<p>设置重试间隔时间默认3秒</p>
<b>函数签名:</b>
@@ -166,6 +165,7 @@ func main() {
```go
func RetryDuration(d time.Duration)
```
<b>例子:</b>
```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
}
```
### <span id="Retry">Retry</span>
<p>重试执行函数retryFunc直到函数运行成功或被context停止</p>
<b>函数签名:</b>
@@ -206,6 +206,7 @@ func main() {
```go
func Retry(retryFunc RetryFunc, opts ...Option) error
```
<b>例子:</b>
```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
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,5 @@
# System
Package system contains some functions about os, runtime, shell command.
<div STYLE="page-break-after: always;"></div>
@@ -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)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/system"
@@ -20,23 +21,23 @@ import (
<div STYLE="page-break-after: always;"></div>
## 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)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="IsWindows">IsWindows</span>
<p>Check if current os is windows.</p>
<b>Signature:</b>
@@ -44,24 +45,23 @@ import (
```go
func IsWindows() bool
```
<b>Example:</b>
```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)
}
```
### <span id="IsLinux">IsLinux</span>
<p>Check if current os is linux.</p>
<b>Signature:</b>
@@ -69,23 +69,23 @@ func main() {
```go
func IsLinux() bool
```
<b>Example:</b>
```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)
}
```
### <span id="IsMac">IsMac</span>
<p>Check if current os is macos.</p>
<b>Signature:</b>
@@ -93,23 +93,23 @@ func main() {
```go
func IsMac() bool
```
<b>Example:</b>
```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)
}
```
### <span id="GetOsEnv">GetOsEnv</span>
<p>Gets the value of the environment variable named by the key.</p>
<b>Signature:</b>
@@ -117,23 +117,23 @@ func main() {
```go
func GetOsEnv(key string) string
```
<b>Example:</b>
```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)
}
```
### <span id="SetOsEnv">SetOsEnv</span>
<p>Sets the value of the environment variable named by the key.</p>
<b>Signature:</b>
@@ -141,24 +141,23 @@ func main() {
```go
func SetOsEnv(key, value string) error
```
<b>Example:</b>
```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)
}
```
### <span id="RemoveOsEnv">RemoveOsEnv</span>
<p>Remove a single environment variable.</p>
<b>Signature:</b>
@@ -166,25 +165,25 @@ func main() {
```go
func RemoveOsEnv(key string) error
```
<b>Example:</b>
```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)
}
}
```
### <span id="CompareOsEnv">CompareOsEnv</span>
<p>Get env named by the key and compare it with comparedEnv.</p>
<b>Signature:</b>
@@ -192,25 +191,24 @@ func main() {
```go
func CompareOsEnv(key, comparedEnv string) bool
```
<b>Example:</b>
```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
}
```
### <span id="ExecCommand">CompareOsEnv</span>
<p>use shell /bin/bash -c(linux) or cmd (windows) to execute command.</p>
<b>Signature:</b>
@@ -218,25 +216,25 @@ func main() {
```go
func ExecCommand(command string) (stdout, stderr string, err error)
```
<b>Example:</b>
```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)
}
```
### <span id="GetOsBits">GetOsBits</span>
<p>获取当前操作系统位数返回32或64</p>
<b>函数签名:</b>
@@ -244,20 +242,17 @@ func main() {
```go
func GetOsBits() int
```
<b>例子:</b>
```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)
}
```

View File

@@ -1,5 +1,6 @@
# System
system包含os, runtime, shell command相关函数。
system 包含 os, runtime, shell command 相关函数。
<div STYLE="page-break-after: always;"></div>
@@ -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)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/system"
@@ -20,23 +21,23 @@ import (
<div STYLE="page-break-after: always;"></div>
## 目录
- [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)
<div STYLE="page-break-after: always;"></div>
## Documentation文档
## Documentation 文档
### <span id="IsWindows">IsWindows</span>
<p>检查当前操作系统是否是windows</p>
<b>Signature:</b>
@@ -44,24 +45,23 @@ import (
```go
func IsWindows() bool
```
<b>Example:</b>
```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)
}
```
### <span id="IsLinux">IsLinux</span>
<p>检查当前操作系统是否是linux</p>
<b>Signature:</b>
@@ -69,23 +69,23 @@ func main() {
```go
func IsLinux() bool
```
<b>Example:</b>
```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)
}
```
### <span id="IsMac">IsMac</span>
<p>检查当前操作系统是否是macos</p>
<b>Signature:</b>
@@ -93,23 +93,23 @@ func main() {
```go
func IsMac() bool
```
<b>Example:</b>
```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)
}
```
### <span id="GetOsEnv">GetOsEnv</span>
<p>获取key命名的环境变量的值</p>
<b>Signature:</b>
@@ -117,23 +117,23 @@ func main() {
```go
func GetOsEnv(key string) string
```
<b>Example:</b>
```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)
}
```
### <span id="SetOsEnv">SetOsEnv</span>
<p>设置由key命名的环境变量的值</p>
<b>Signature:</b>
@@ -141,24 +141,23 @@ func main() {
```go
func SetOsEnv(key, value string) error
```
<b>Example:</b>
```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)
}
```
### <span id="RemoveOsEnv">RemoveOsEnv</span>
<p>删除单个环境变量</p>
<b>Signature:</b>
@@ -166,25 +165,25 @@ func main() {
```go
func RemoveOsEnv(key string) error
```
<b>Example:</b>
```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)
}
}
```
### <span id="CompareOsEnv">CompareOsEnv</span>
<p>获取key命名的环境变量值并与compareEnv进行比较</p>
<b>Signature:</b>
@@ -192,25 +191,24 @@ func main() {
```go
func CompareOsEnv(key, comparedEnv string) bool
```
<b>Example:</b>
```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
}
```
### <span id="ExecCommand">CompareOsEnv</span>
<p>使用shell /bin/bash -c(linux) 或 cmd (windows) 执行shell命令</p>
<b>Signature:</b>
@@ -218,25 +216,25 @@ func main() {
```go
func ExecCommand(command string) (stdout, stderr string, err error)
```
<b>Example:</b>
```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)
}
```
### <span id="GetOsBits">GetOsBits</span>
<p>Get current os bits, 32bit or 64bit. return 32 or 64</p>
<b>Signature:</b>
@@ -244,20 +242,17 @@ func main() {
```go
func GetOsBits() int
```
<b>Example:</b>
```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)
}
```

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff