1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-03-01 00:35:28 +08:00

Compare commits

...

8 Commits

Author SHA1 Message Date
dudaodong 6c3dc3e7d6 Merge branch 'rc' of github.com:duke-git/lancet into rc 2025-10-31 14:59:25 +08:00
dudaodong 2a2e1ca551 doc: add enum and update overview index 2025-10-31 14:57:54 +08:00
dudaodong e1821eed2c doc: add docment for enum package 2025-10-31 14:48:32 +08:00
dudaodong 62f0a96d91 doc: add docment for enum package 2025-10-31 14:48:22 +08:00
dudaodong cbdc3971dd doc: add docment for new or fixed function 2025-10-31 13:37:41 +08:00
dudaodong f407e51b24 fix: fix issue #335 2025-10-30 17:09:48 +08:00
dudaodong 3c6c3a14cf Merge branch 'rc' into v2 2025-10-29 21:10:54 +08:00
dudaodong 41bafdef92 refact: remove unused code 2025-10-29 21:10:30 +08:00
25 changed files with 2589 additions and 439 deletions
+30
View File
@@ -1125,6 +1125,10 @@ import "github.com/duke-git/lancet/v2/maputil"
- **<big>FindValuesBy</big>** : returns a slice of values from the map that satisfy the given predicate function. - **<big>FindValuesBy</big>** : returns a slice of values from the map that satisfy the given predicate function.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/maputil.md#FindValuesBy)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/maputil.md#FindValuesBy)]
[[play](https://go.dev/play/p/bvNwNBZDm6v)] [[play](https://go.dev/play/p/bvNwNBZDm6v)]
- **<big>ToMarkdownTable</big>** : Convert a map slice data to a Markdown table string. It supports custom header display names and column display order.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/maputil.md#ToMarkdownTable)]
[[play](https://go.dev/play/p/todo)]
<h3 id="mathutil"> 13. Mathutil package implements some functions for math calculation. &nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">index</a></h3> <h3 id="mathutil"> 13. Mathutil package implements some functions for math calculation. &nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">index</a></h3>
@@ -1822,30 +1826,50 @@ import "github.com/duke-git/lancet/v2/structs"
- **<big>New</big>** : creates a `Struct` instance. - **<big>New</big>** : creates a `Struct` instance.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#New)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#New)]
[[play](https://go.dev/play/p/O29l8kk-Z17)]
- **<big>ToMap</big>** : converts a valid struct to a map. - **<big>ToMap</big>** : converts a valid struct to a map.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#ToMap)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#ToMap)]
[[play](https://go.dev/play/p/qQbLySBgerZ)]
- **<big>Fields</big>** : get all fields of a given struct, that the fields are abstract struct field. - **<big>Fields</big>** : get all fields of a given struct, that the fields are abstract struct field.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Fields)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Fields)]
[[play](https://go.dev/play/p/w3Kk_CyVY7D)]
- **<big>Field</big>** : get an abstract field of a struct by given field name
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Field)]
[[play](https://go.dev/play/p/KocZMSYarza)]
- **<big>IsStruct</big>** : check if the struct is valid. - **<big>IsStruct</big>** : check if the struct is valid.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsStruct)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsStruct)]
[[play](https://go.dev/play/p/bU2FSdkbK1C)]
- **<big>Tag</big>** : get a `Tag` of the `Field`, `Tag` is a abstract struct field tag. - **<big>Tag</big>** : get a `Tag` of the `Field`, `Tag` is a abstract struct field tag.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Tag)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Tag)]
[[play](https://go.dev/play/p/DVrx5HvvUJr)]
- **<big>Name</big>** : get the field name. - **<big>Name</big>** : get the field name.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Name)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Name)]
[[play](https://go.dev/play/p/zfIGlqsatee)]
- **<big>Value</big>** : get the `Field` underlying value. - **<big>Value</big>** : get the `Field` underlying value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Value)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Value)]
[[play](https://go.dev/play/p/qufYEU2o4Oi)]
- **<big>Kind</big>** : get the field's kind. - **<big>Kind</big>** : get the field's kind.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Kind)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#Kind)]
[[play](https://go.dev/play/p/wg4NlcUNG5o)]
- **<big>IsEmbedded</big>** : check if the field is an embedded field. - **<big>IsEmbedded</big>** : check if the field is an embedded field.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsEmbedded)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsEmbedded)]
[[play](https://go.dev/play/p/wV2PrbYm3Ec)]
- **<big>IsExported</big>** : check if the field is exported. - **<big>IsExported</big>** : check if the field is exported.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsExported)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsExported)]
[[play](https://go.dev/play/p/csK4AXYaNbJ)]
- **<big>IsZero</big>** : check if the field is zero value. - **<big>IsZero</big>** : check if the field is zero value.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsZero)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsZero)]
[[play](https://go.dev/play/p/RzqpGISf87r)]
- **<big>IsSlice</big>** : check if the field is a slice. - **<big>IsSlice</big>** : check if the field is a slice.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsSlice)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsSlice)]
[[play](https://go.dev/play/p/MKz4CgBIUrU)]
- **<big>IsTargetType</big>** : check if the field is target type. - **<big>IsTargetType</big>** : check if the field is target type.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsTargetType)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#IsTargetType)]
[[play](https://go.dev/play/p/Ig75P-agN39)]
- **<big>TypeName</big>** : Return struct type name.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/struct.md#TypeName)]
[[play](https://go.dev/play/p/todo)]
<h3 id="strutil"> 21. Strutil package contains some functions to manipulate string. &nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">index</a></h3> <h3 id="strutil"> 21. Strutil package contains some functions to manipulate string. &nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">index</a></h3>
@@ -2304,6 +2328,12 @@ import "github.com/duke-git/lancet/v2/validator"
- **<big>IsChinaUnionPay</big>** : check if a give string is a valid china union pay number or not. - **<big>IsChinaUnionPay</big>** : check if a give string is a valid china union pay number or not.
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/validator.md#IsChinaUnionPay)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/validator.md#IsChinaUnionPay)]
[[play](https://go.dev/play/p/yafpdxLiymu)] [[play](https://go.dev/play/p/yafpdxLiymu)]
- **<big>IsPassport</big>** : Passport validation(using regex).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/validator.md#IsPassport)]
[[play](https://go.dev/play/p/todo)]
- **<big>IsChineseHMPassport</big>** : Mainland travel permit for Hong Kong, Macao validation (using regex).
[[doc](https://github.com/duke-git/lancet/blob/main/docs/en/api/packages/validator.md#IsChineseHMPassport)]
[[play](https://go.dev/play/p/todo)]
<h3 id="xerror"> 25. Xerror package implements helpers for errors. &nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">index</a></h3> <h3 id="xerror"> 25. Xerror package implements helpers for errors. &nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">index</a></h3>
+27 -1
View File
@@ -1135,6 +1135,9 @@ import "github.com/duke-git/lancet/v2/maputil"
- **<big>FindValuesBy</big>** : 返回一个切片,包含满足给定谓词判断函数的 map 中的值。 - **<big>FindValuesBy</big>** : 返回一个切片,包含满足给定谓词判断函数的 map 中的值。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md#FindValuesBy)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md#FindValuesBy)]
[[play](https://go.dev/play/p/bvNwNBZDm6v)] [[play](https://go.dev/play/p/bvNwNBZDm6v)]
- **<big>ToMarkdownTable</big>** : 将一个 map 切片数据转换为 Markdown 表格字符串。支持自定义表头显示名称和列的显示顺序。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/maputil.md#ToMarkdownTable)]
[[play](https://go.dev/play/p/todo)]
<h3 id="mathutil"> 14. mathutil 包实现了一些数学计算的函数。&nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">回到目录</a></h3> <h3 id="mathutil"> 14. mathutil 包实现了一些数学计算的函数。&nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">回到目录</a></h3>
@@ -1828,32 +1831,50 @@ import "github.com/duke-git/lancet/v2/structs"
- **<big>New</big>** : `Struct`结构体的构造函数。 - **<big>New</big>** : `Struct`结构体的构造函数。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#New)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#New)]
[[play](https://go.dev/play/p/O29l8kk-Z17)]
- **<big>ToMap</big>** : 将一个合法的 struct 对象转换为 map[string]any。 - **<big>ToMap</big>** : 将一个合法的 struct 对象转换为 map[string]any。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#ToMap)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#ToMap)]
[[play](https://go.dev/play/p/qQbLySBgerZ)]
- **<big>Fields</big>** : 获取一个 struct 对象的属性列表。 - **<big>Fields</big>** : 获取一个 struct 对象的属性列表。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Fields)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Fields)]
[[play](https://go.dev/play/p/w3Kk_CyVY7D)]
- **<big>Field</big>** : 根据属性名获取一个 struct 对象的属性。 - **<big>Field</big>** : 根据属性名获取一个 struct 对象的属性。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Fields)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Fields)]
[[play](https://go.dev/play/p/KocZMSYarza)]
- **<big>IsStruct</big>** : 判断是否为一个合法的 struct 对象。 - **<big>IsStruct</big>** : 判断是否为一个合法的 struct 对象。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsStruct)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsStruct)]
[[play](https://go.dev/play/p/bU2FSdkbK1C)]
- **<big>Tag</big>** : 获取`Field``Tag`,默认的 tag key 是 json。 - **<big>Tag</big>** : 获取`Field``Tag`,默认的 tag key 是 json。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Tag)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Tag)]
[[play](https://go.dev/play/p/DVrx5HvvUJr)]
- **<big>Name</big>** : 获取属性名。 - **<big>Name</big>** : 获取属性名。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Name)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Name)]
[[play](https://go.dev/play/p/zfIGlqsatee)]
- **<big>Value</big>** : 获取`Field`属性的值。 - **<big>Value</big>** : 获取`Field`属性的值。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Value)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Value)]
[[play](https://go.dev/play/p/qufYEU2o4Oi)]
- **<big>Kind</big>** : 获取属性 Kind。 - **<big>Kind</big>** : 获取属性 Kind。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Kind)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#Kind)]
[[play](https://go.dev/play/p/wg4NlcUNG5o)]
- **<big>IsEmbedded</big>** : 判断属性是否为嵌入。 - **<big>IsEmbedded</big>** : 判断属性是否为嵌入。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsEmbedded)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsEmbedded)]
[[play](https://go.dev/play/p/wV2PrbYm3Ec)]
- **<big>IsExported</big>** : 判断属性是否导出。 - **<big>IsExported</big>** : 判断属性是否导出。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsExported)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsExported)]
[[play](https://go.dev/play/p/csK4AXYaNbJ)]
- **<big>IsZero</big>** : 判断属性是否为零值。 - **<big>IsZero</big>** : 判断属性是否为零值。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsZero)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsZero)]
[[play](https://go.dev/play/p/RzqpGISf87r)]
- **<big>IsSlice</big>** : 判断属性是否是切片。 - **<big>IsSlice</big>** : 判断属性是否是切片。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsSlice)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsSlice)]
[[play](https://go.dev/play/p/MKz4CgBIUrU)]
- **<big>IsTargetType</big>** : 判断属性是否是目标类型。 - **<big>IsTargetType</big>** : 判断属性是否是目标类型。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsTargetType)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#IsTargetType)]
[[play](https://go.dev/play/p/Ig75P-agN39)]
- **<big>TypeName</big>** : 获取结构体类型名。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/struct.md#TypeName)]
[[play](https://go.dev/play/p/todo)]
<h3 id="strutil"> 22. strutil 包含字符串处理的相关函数。&nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">回到目录</a></h3> <h3 id="strutil"> 22. strutil 包含字符串处理的相关函数。&nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">回到目录</a></h3>
@@ -2313,7 +2334,12 @@ import "github.com/duke-git/lancet/v2/validator"
- **<big>IsChinaUnionPay</big>** : 检查字符串是否是有效的中国银联卡号。 - **<big>IsChinaUnionPay</big>** : 检查字符串是否是有效的中国银联卡号。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/validator.md#IsChinaUnionPay)] [[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/validator.md#IsChinaUnionPay)]
[[play](https://go.dev/play/p/yafpdxLiymu)] [[play](https://go.dev/play/p/yafpdxLiymu)]
- **<big>IsPassport</big>** : 判断护照(正则判断)。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/validator.md#IsPassport)]
[[play](https://go.dev/play/p/todo)]
- **<big>IsChineseHMPassport</big>** : 判断港澳台通行证(正则判断)。
[[doc](https://github.com/duke-git/lancet/blob/main/docs/api/packages/validator.md#IsChineseHMPassport)]
[[play](https://go.dev/play/p/todo)]
<h3 id="xerror"> 26. xerror 包实现一些错误处理函数。&nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">回到目录</a></h3> <h3 id="xerror"> 26. xerror 包实现一些错误处理函数。&nbsp; &nbsp; &nbsp; &nbsp;<a href="#index">回到目录</a></h3>
```go ```go
+49 -49
View File
@@ -1,51 +1,51 @@
-----BEGIN rsa private key----- -----BEGIN rsa private key-----
MIIJKAIBAAKCAgEAudV/zW+ycOExUja9W3ZyhKWA2TN+FqTzfZKPB+btwe4Md0WJ MIIJKQIBAAKCAgEAv25yPU83rpR+acaNoyEOrIBo3gBcykscNL1vbMDbYc5jYib7
TM0+ZdT8UXujltTEWSUhY/qkOiNIutF2CiFWonDQeNzMobLB/pmq1P0Z+LVH4ERs BvxoOkdfeIhjTIDfMVzkzBXAC0eNbMey1/nCcjoFNPXDShsyig8paDl7PG0IVOYp
bcl9zYCfpvTsnIqzjuPe30iozK0Er03qBxsHnWV3WbIl3+1f17T6OD5CkdT+9RCI uXDQ/vi82F7rrXehESrImIBPPDTrZWeg3jqFVkZt6QnB/j7dMKPMeJcarLvwMDKq
D1EqsQ+9aGIeR6cmoB+rxjPLb0xc5oS1hbb3FkiT7VLI2doeqP8Pmwdohbh7XmgJ TM3xguPAAoCAEy9Lylu2zncI8BPyhvz+++j0jBdRl8RYHUyE60BIEROFcHI7lnWM
Qkok+ALxKQ4bCMJ780k2KigKGjXxKlYJq1ZF301sbhvTo2cSci4ieXP0A4B4swSz oH/Uj8cWu8aTRPtNZdk4l9hBHotfi7qvO9b4jB/75Qko/MY5YyrohAwQN/f9zVuT
LKl0G7IX/UbYACn3qNecvQt5OtFM644mqfSUffFg7PefZVZhaUytvU92W+b0LXF2 tlfFxKCb1+5Lxq4v4llwUv9eA7euMJf/nDU29m4Oshu7snkYgwB4Cd+bVqS8z9vW
NbjhtVES5HByDwjjF/KOfV7U/o+YmAjlakieYM7pcggfgfqyZWdF70nSvgPgVt5q +brXtP6ZZTJls6pBX4FFukNkCUgiNBuUVDO04AUNSBfAxiHXS88zLdrTRIfM9Mdg
tOnYPeUrQV2aUmZE+BagOQ/HAIKPbhmyMEA3odgqaALsvD/58iVv9syqEEm5trLY oGQapqHaiieQ4GdFbndKfck0AfoSXy0NtWOX4/IZWUphqnyAKO1w8hzK1iydgv4m
A/p2uo0yv3iHrEggEZk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akVTZpNJ380 BKazByfDK8yttwTCtut5yyR5fj1GDBpKZJ3qj0B/GxWPlbhgRz4qjDpzlAhhLz3X
wgibNifNJ0HhZf61CZvn9gGTOMpbkYgud18p7VYV9WFw54KGdRn1QKLSBjNCB9Vm m/LD4QthjNy6Y7F0xB/2EdvdysEaAOUutGZkBWL7kIMUJP9EBhr4ckxUnhFpgtMG
FznoA6w2WF2zasucKAEc+JaPE1WaGqbDAoIBAC4yD/r30E3itMDKyhlHzkRT4NNx Wwv46p8cVqGAMem6sdDdvasJGT9V62NxAoIBAQDBZ8zVRyZAHGPclJPZ8JtDuaI2
X/6gGE2RPwoP8UhMyYiBh1cbtqSZE0zXsO8I02GnJ362boG/LOtMkCBbwH1tfDKU m9tIP2eXefsnAaaSpyQlpEHCr+XmxhkKT0mRIw7y+zR1micmiD2gRu/2ITvcs19x
1iL9obUEf56JGWyPL/OTbJzcUYgiIvH7R2HGRaLd1ybiAdFjM/VNVyV/855mM7J2 DIPidRt9gmqicGmQvIJYdYXJ+g+94XPVtC3l8dyIdHVndPsaqs+ADsjw5tQKwgAQ
zWcPLR/KdHv4vlrckZW2kqG4ai/PwY8EG4TjPkhkx90gy6XLtwXnIwdsNAXYsHh4 s4JIcc80un4EbHch3Fa0UOKwj79pV5yWeXHN6diudjyF7yYhVkl9TlHG3NeHsepN
dAyQNiHh1Ucr8Id0FVIHuOERjCoaSCttznzQIH+I6RKwFVxNqsRrMQaZBYPMab4X WHsf2qQQgGRjR3D1a3AkjPuaQWxg+3YnVO4KAuem55QGhEvuYATd/elxzN3MVtJC
9G4exHRJ/02wJHTHKMeU7Ew15quV4+v19HgJp5Yu6Ne1Hu1sz7XGMtOhUPM= 9MAghroYilaN7RtA4tmXLb9d0LBxHzYpyANNlpCSRvDoJsLgPSbrvwbkjAlL
-----END rsa private key----- -----END rsa private key-----
+12 -12
View File
@@ -1,14 +1,14 @@
-----BEGIN rsa public key----- -----BEGIN rsa public key-----
MIICIjANBgkqhkiG9w0BAQEFAA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hzK1iydgv4mHpjKr5I3sh1ARh9baNUXLH2A9rTQvk3fXsK7
Hs0ANg+7NIJR9joKvXGJkg8E2thpg9UKl/Z2astZk7o92trMp5DQW1vjV7JW+mEQ RRkwP8gH9BKvtQiHfVVqAh9MPdPygHiOUgGgqTQj2xb1KXS1yzJVcgDFYNv8NrE1
dztQxE5NgeE8cI/BdqMSyvG2UA7u5LqBHXx35s3gPva+eutKnTcRpO3T01PH2sba M8EdCaItfRWU7MkzecGriQFQ42AvIMFLMyD25hXDj/mZgaw1CgGoemMJoAm+yu1N
iXiiNG5oFUYjocikhY7f3TUCAwEAAQ== RUB4dW1vHqn/UxhcWHrLhJsCAwEAAQ==
-----END rsa public key----- -----END rsa public key-----
+2 -1
View File
@@ -114,6 +114,7 @@ export const enConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
], ],
}, },
{ text: 'datetime', link: '/en/api/packages/datetime' }, { text: 'datetime', link: '/en/api/packages/datetime' },
{ text: 'enum', link: '/en/api/packages/enum' },
{ text: 'eventbus', link: '/en/api/packages/eventbus' }, { text: 'eventbus', link: '/en/api/packages/eventbus' },
{ text: 'fileutil', link: '/en/api/packages/fileutil' }, { text: 'fileutil', link: '/en/api/packages/fileutil' },
{ text: 'formatter', link: '/en/api/packages/formatter' }, { text: 'formatter', link: '/en/api/packages/formatter' },
@@ -128,9 +129,9 @@ export const enConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
{ text: 'stream', link: '/en/api/packages/stream' }, { text: 'stream', link: '/en/api/packages/stream' },
{ text: 'struct', link: '/en/api/packages/struct' }, { text: 'struct', link: '/en/api/packages/struct' },
{ text: 'strutil', link: '/en/api/packages/strutil' }, { text: 'strutil', link: '/en/api/packages/strutil' },
{ text: 'system', link: '/en/api/packages/system' },
{ text: 'tuple', link: '/en/api/packages/tuple' }, { text: 'tuple', link: '/en/api/packages/tuple' },
{ text: 'validator', link: '/en/api/packages/validator' }, { text: 'validator', link: '/en/api/packages/validator' },
{ text: 'system', link: '/en/api/packages/system' },
{ text: 'xerror', link: '/en/api/packages/xerror' }, { text: 'xerror', link: '/en/api/packages/xerror' },
], ],
}, },
+3 -2
View File
@@ -128,7 +128,7 @@ export const zhConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
}, },
{ text: '日期&时间', link: '/api/packages/datetime' }, { text: '日期&时间', link: '/api/packages/datetime' },
{ text: '事件总线', link: '/api/packages/eventbus' }, { text: '事件总线', link: '/api/packages/eventbus' },
{ text: '文件', link: '/api/packages/fileutil' }, { text: '文件处理', link: '/api/packages/fileutil' },
{ text: '格式化工具', link: '/api/packages/formatter' }, { text: '格式化工具', link: '/api/packages/formatter' },
{ text: '函数', link: '/api/packages/function' }, { text: '函数', link: '/api/packages/function' },
{ text: '数学工具', link: '/api/packages/mathutil' }, { text: '数学工具', link: '/api/packages/mathutil' },
@@ -141,9 +141,10 @@ export const zhConfig: LocaleSpecificConfig<DefaultTheme.Config> = {
{ text: '流', link: '/api/packages/stream' }, { text: '流', link: '/api/packages/stream' },
{ text: '结构体', link: '/api/packages/struct' }, { text: '结构体', link: '/api/packages/struct' },
{ text: '字符串', link: '/api/packages/strutil' }, { text: '字符串', link: '/api/packages/strutil' },
{ text: '系统', link: '/api/packages/system' }, { text: '枚举', link: '/api/packages/enum' },
{ text: '元组', link: '/api/packages/tuple' }, { text: '元组', link: '/api/packages/tuple' },
{ text: '验证器', link: '/api/packages/validator' }, { text: '验证器', link: '/api/packages/validator' },
{ text: '系统工具函数', link: '/api/packages/system' },
{ text: '错误处理', link: '/api/packages/xerror' }, { text: '错误处理', link: '/api/packages/xerror' },
], ],
}, },
+1
View File
@@ -46,6 +46,7 @@ outline: deep
<div class="package-cell">cryptor</div> <div class="package-cell">cryptor</div>
<div class="package-cell">datastructure</div> <div class="package-cell">datastructure</div>
<div class="package-cell">datetime</div> <div class="package-cell">datetime</div>
<div class="package-cell">enum</div>
<div class="package-cell">eventbus</div> <div class="package-cell">eventbus</div>
<div class="package-cell">fileutil</div> <div class="package-cell">fileutil</div>
<div class="package-cell">formatter</div> <div class="package-cell">formatter</div>
+850
View File
@@ -0,0 +1,850 @@
# Enum
Enum实现一个简单枚举工具包。
<div STYLE="page-break-after: always;"></div>
## 源码:
- [https://github.com/duke-git/lancet/blob/main/enum/enum.go](https://github.com/duke-git/lancet/blob/main/enum/enum.go)
<div STYLE="page-break-after: always;"></div>
## 用法:
```go
import (
"github.com/duke-git/lancet/v2/enum"
)
```
<div STYLE="page-break-after: always;"></div>
## 目录
- [NewItem](#NewItem)
- [NewItemsFromPairs](#NewItemsFromPairs)
- [Value](#Value)
- [Name](#Name)
- [Valid](#Valid)
- [MarshalJSON](#MarshalJSON)
- [NewRegistry](#NewRegistry)
- [Add](#Add)
- [Remove](#Remove)
- [Update](#Update)
- [GetByValue](#GetByValue)
- [GetByName](#GetByName)
- [Items](#Items)
- [Contains](#Contains)
- [Size](#Size)
- [Range](#Range)
- [SortedItems](#SortedItems)
- [Filter](#Filter)
<div STYLE="page-break-after: always;"></div>
## 文档
### <span id="NewItem">NewItem</span>
<p>创建枚举项。</p>
<b>函数签名:</b>
```go
func NewItem[T comparable](value T, name string) *Item[T]
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
fmt.Println(item1.Name(), item1.Value())
fmt.Println(item2.Name(), item2.Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="NewItemsFromPairs">NewItemsFromPairs</span>
<p>从Pair结构体的切片创建枚举项。</p>
<b>函数签名:</b>
```go
func NewItemsFromPairs[T comparable](pairs ...Pair[T]) []*Item[T]
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
items := enum.NewItemsFromPairs(
enum.Pair[Status]{Value: Active, Name: "Active"},
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
)
fmt.Println(items[0].Name(), items[0].Value())
fmt.Println(items[1].Name(), items[1].Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Value">Value</span>
<p>返回枚举项的值。</p>
<b>函数签名:</b>
```go
func (it *Item[T]) Value() T
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
items := enum.NewItemsFromPairs(
enum.Pair[Status]{Value: Active, Name: "Active"},
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
)
fmt.Println(items[0].Name(), items[0].Value())
fmt.Println(items[1].Name(), items[1].Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Name">Name</span>
<p>返回枚举项的名称。</p>
<b>函数签名:</b>
```go
func (it *Item[T]) Name() string
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
items := enum.NewItemsFromPairs(
enum.Pair[Status]{Value: Active, Name: "Active"},
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
)
fmt.Println(items[0].Name(), items[0].Value())
fmt.Println(items[1].Name(), items[1].Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Valid">Valid</span>
<p>检查枚举项是否有效。如果提供了自定义检查函数,将使用该函数验证值。</p>
<b>函数签名:</b>
```go
func (it *Item[T]) Valid(checker ...func(T) bool) bool
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
item := enum.NewItem(Active, "Active")
fmt.Println(item.Valid())
invalidItem := enum.NewItem(Unknown, "")
fmt.Println(invalidItem.Valid())
// Output:
// true
// false
}
```
### <span id="MarshalJSON">MarshalJSON</span>
<p>枚举项实现json.Marshaler 接口。</p>
<b>函数签名:</b>
```go
func (it *Item[T]) MarshalJSON() ([]byte, error)
func (it *Item[T]) UnmarshalJSON(data []byte) error
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
item := enum.NewItem(Active, "Active")
data, _ := item.MarshalJSON()
fmt.Println(string(data))
var unmarshaledItem Item[Status]
_ = unmarshaledItem.UnmarshalJSON(data)
fmt.Println(unmarshaledItem.Name(), unmarshaledItem.Value())
// Output:
// {"name":"Active","value":1}
// Active 1
}
```
### <span id="NewRegistry">NewRegistry</span>
<p>Registry 定义了一个通用的枚举注册表结构体。</p>
<b>函数签名:</b>
```go
func NewRegistry[T comparable](items ...*Item[T]) *Registry[T]
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
if item, found := registry.GetByValue(Active); found {
fmt.Println("Found by value:", item.Name())
}
if item, found := registry.GetByName("Inactive"); found {
fmt.Println("Found by name:", item.Value())
}
// Output:
// Found by value: Active
// Found by name: 2
}
```
### <span id="Add">Add</span>
<p>向枚举注册表添加枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Add(items ...*Item[T])
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
if item, found := registry.GetByValue(Active); found {
fmt.Println("Found by value:", item.Name())
}
if item, found := registry.GetByName("Inactive"); found {
fmt.Println("Found by name:", item.Value())
}
// Output:
// Found by value: Active
// Found by name: 2
}
```
### <span id="Remove">Remove</span>
<p>在枚举注册表中删除枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Remove(value T) bool
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
registry.Add(item1)
fmt.Println("Size before removal:", registry.Size())
removed := registry.Remove(Active)
fmt.Println("Removed:", removed)
fmt.Println("Size after removal:", registry.Size())
// Output:
// Size before removal: 1
// Removed: true
// Size after removal: 0
}
```
### <span id="Update">Update</span>
<p>在枚举注册表中更新枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Update(value T, newName string) bool
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
registry.Add(item1)
updated := registry.Update(Active, "Activated")
fmt.Println("Updated:", updated)
if item, found := registry.GetByValue(Active); found {
fmt.Println("New name:", item.Name())
}
// Output:
// Updated: true
// New name: Activated
}
```
### <span id="GetByValue">GetByValue</span>
<p>在枚举注册表中通过值获取枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) GetByValue(value T) (*Item[T], bool)
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
registry.Add(item1, item2)
if item, found := registry.GetByValue(Active); found {
fmt.Println("Found name by value:", item.Name())
}
// Output:
// Found name by value: Active
}
```
### <span id="GetByName">GetByName</span>
<p>在枚举注册表中通过名称获取枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) GetByName(name string) (*Item[T], bool)
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item := enum.NewItem(Active, "Active")
registry.Add(item)
if item, found := registry.GetByName("Active"); found {
fmt.Println("Found value by name:", item.Value())
}
// Output:
// Found value by name: 1
}
```
### <span id="Items">Items</span>
<p>返回枚举注册表中的枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Items() []*Item[T]
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
for _, item := range registry.Items() {
fmt.Println(item.Name(), item.Value())
}
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Contains">Contains</span>
<p>检查注册表中是否存在具有给定值的枚举项。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Contains(value T) bool
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item := enum.NewItem(Active, "Active")
registry.Add(item)
fmt.Println(registry.Contains(Active))
fmt.Println(registry.Contains(Inactive))
// Output:
// true
// false
}
```
### <span id="Size">Size</span>
<p>返回注册表中枚举项的数目。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Size() int
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
fmt.Println("Initial size:", registry.Size())
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
fmt.Println("Size after adding items:", registry.Size())
registry.Remove(Active)
fmt.Println("Size after removing an item:", registry.Size())
// Output:
// Initial size: 0
// Size after adding items: 2
// Size after removing an item: 1
}
```
### <span id="Range">Range</span>
<p>遍历注册表中的所有枚举项,并应用给定的函数。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Range(fn func(*Item[T]) bool)
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
registry.Range(func(item *Item[Status]) bool {
fmt.Println(item.Name(), item.Value())
return true // continue iteration
})
// Output:
// Active 1
// Inactive 2
}
```
### <span id="SortedItems">SortedItems</span>
<p>返回按给定比较函数排序的所有枚举项的切片。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) SortedItems(less func(*Item[T], *Item[T]) bool) []*Item[T]
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Inactive, "Inactive")
item2 := enum.NewItem(Active, "Active")
registry.Add(item1, item2)
for _, item := range registry.SortedItems(func(i1, i2 *Item[Status]) bool {
return i1.value < i2.value
}) {
fmt.Println(item.Name(), item.Value())
}
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Filter">Filter</span>
<p>返回满足给定谓词函数的枚举项切片。</p>
<b>函数签名:</b>
```go
func (r *Registry[T]) Filter(predicate func(*Item[T]) bool) []*Item[T]
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
activeItems := registry.Filter(func(item *Item[Status]) bool {
return item.Value() == Active
})
for _, item := range activeItems {
fmt.Println(item.Name(), item.Value())
}
// Output:
// Active 1
}
```
+1 -1
View File
@@ -2357,7 +2357,7 @@ func main() {
编辑 编辑
func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string
``` ```
<b>示例:<span style="float:right;display:inline-block;">[运行]()</span></b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go ```go
+60 -17
View File
@@ -31,6 +31,7 @@ import (
- [IsStruct](#IsStruct) - [IsStruct](#IsStruct)
- [Tag](#Tag) - [Tag](#Tag)
- [Name](#Name) - [Name](#Name)
- [TypeName](#TypeName)
- [Value](#Value) - [Value](#Value)
- [Kind](#Kind) - [Kind](#Kind)
- [IsEmbedded](#IsEmbedded) - [IsEmbedded](#IsEmbedded)
@@ -53,7 +54,7 @@ import (
func New(value any, tagName ...string) *Struct func New(value any, tagName ...string) *Struct
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/O29l8kk-Z17)</span></b>
```go ```go
package main package main
@@ -68,7 +69,11 @@ func main() {
} }
p1 := &People{Name: "11"} p1 := &People{Name: "11"}
s := structs.New(p1) s := structs.New(p1)
// to do something
fmt.Println(s.ToMap())
// Output:
// map[name:11] <nil>
} }
``` ```
@@ -88,7 +93,7 @@ func (s *Struct) ToMap() (map[string]any, error)
func ToMap(v any) (map[string]any, error) func ToMap(v any) (map[string]any, error)
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/qQbLySBgerZ)</span></b>
```go ```go
package main package main
@@ -129,7 +134,7 @@ func main() {
func (s *Struct) Fields() []*Field func (s *Struct) Fields() []*Field
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/w3Kk_CyVY7D)</span></b>
```go ```go
package main package main
@@ -161,10 +166,10 @@ func main() {
<b>函数签名:</b> <b>函数签名:</b>
```go ```go
func (s *Struct) Field(name string) *Field func (s *Struct) Field(name string) (*Field, bool)
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/KocZMSYarza)</span></b>
```go ```go
package main package main
@@ -180,12 +185,14 @@ func main() {
} }
p1 := &People{Name: "11"} p1 := &People{Name: "11"}
s := structs.New(p1) s := structs.New(p1)
f := s.Field("Name") f, found := s.Field("Name")
fmt.Println(f.Value()) fmt.Println(f.Value())
fmt.Println(found)
// Output: // Output:
// 11 // 11
// true
} }
``` ```
@@ -199,7 +206,7 @@ func main() {
func (s *Struct) IsStruct() bool func (s *Struct) IsStruct() bool
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/bU2FSdkbK1C)</span></b>
```go ```go
package main package main
@@ -233,7 +240,7 @@ func main() {
func (f *Field) Tag() *Tag func (f *Field) Tag() *Tag
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/DVrx5HvvUJr)</span></b>
```go ```go
package main package main
@@ -270,7 +277,7 @@ func main() {
func (f *Field) Value() any func (f *Field) Value() any
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/qufYEU2o4Oi)</span></b>
```go ```go
package main package main
@@ -306,7 +313,7 @@ func main() {
func (f *Field) IsEmbedded() bool func (f *Field) IsEmbedded() bool
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/wV2PrbYm3Ec)</span></b>
```go ```go
package main package main
@@ -351,7 +358,7 @@ func main() {
func (f *Field) IsExported() bool func (f *Field) IsExported() bool
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/csK4AXYaNbJ)</span></b>
```go ```go
package main package main
@@ -390,7 +397,7 @@ func main() {
func (f *Field) IsZero() bool func (f *Field) IsZero() bool
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/RzqpGISf87r)</span></b>
```go ```go
package main package main
@@ -429,7 +436,7 @@ func main() {
func (f *Field) Name() string func (f *Field) Name() string
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/zfIGlqsatee)</span></b>
```go ```go
package main package main
@@ -468,7 +475,7 @@ func main() {
func (f *Field) Kind() reflect.Kind func (f *Field) Kind() reflect.Kind
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/wg4NlcUNG5o)</span></b>
```go ```go
package main package main
@@ -497,6 +504,42 @@ func main() {
} }
``` ```
### <span id="TypeName">TypeName</span>
<p>获取结构体类型名。</p>
<b>函数签名:</b>
```go
func (s *Struct) TypeName() string
```
<b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p := &Parent{Age: 11}
s := structs.New(p1)
fmt.Println(s.TypeName())
// Output:
// Parent
}
```
### <span id="IsSlice">IsSlice</span> ### <span id="IsSlice">IsSlice</span>
<p>判断属性是否是切片</p> <p>判断属性是否是切片</p>
@@ -507,7 +550,7 @@ func main() {
func (f *Field) IsSlice() bool func (f *Field) IsSlice() bool
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/MKz4CgBIUrU)</span></b>
```go ```go
package main package main
@@ -544,7 +587,7 @@ func main() {
func (f *Field) IsTargetType(targetType reflect.Kind) bool func (f *Field) IsTargetType(targetType reflect.Kind) bool
``` ```
<b>示例:</b> <b>示例:<span style="float:right;display:inline-block;">[运行](https://go.dev/play/p/Ig75P-agN39)</span></b>
```go ```go
package main package main
+91 -12
View File
@@ -65,6 +65,8 @@ import (
- [IsAmericanExpress](#IsAmericanExpress) - [IsAmericanExpress](#IsAmericanExpress)
- [IsUnionPay](#IsUnionPay) - [IsUnionPay](#IsUnionPay)
- [IsChinaUnionPay](#IsChinaUnionPay) - [IsChinaUnionPay](#IsChinaUnionPay)
- [IsPassport](#IsPassport)
- [IsChineseHMPassport](#IsChineseHMPassport)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
@@ -844,20 +846,20 @@ import (
func main() { func main() {
result1 := validator.IsAlphaNumeric("ABC") result1 := validator.IsAlphaNumeric("ABC")
result2 := validator.IsAlphaNumeric("123") result2 := validator.IsAlphaNumeric("123")
result3 := validator.IsAlphaNumeric("abc123") result3 := validator.IsAlphaNumeric("abc123")
result4 := validator.IsAlphaNumeric("abc123@#$") result4 := validator.IsAlphaNumeric("abc123@#$")
fmt.Println(result1) fmt.Println(result1)
fmt.Println(result2) fmt.Println(result2)
fmt.Println(result3) fmt.Println(result3)
fmt.Println(result4) fmt.Println(result4)
// Output: // Output:
// true // true
// true // true
// true // true
// false // false
} }
``` ```
@@ -1567,3 +1569,80 @@ func main() {
// false // false
} }
``` ```
### <span id="IsPassport">IsPassport</span>
<p>判断护照(正则判断)。</p>
<b>函数签名:</b>
```go
func IsPassport(passport, country string) bool
```
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/todo)</span></b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsPassport("P123456789", "CN")
result2 := validator.IsPassport("123456789", "US")
result3 := validator.IsPassport("AB1234567", "RU")
result4 := validator.IsPassport("123456789", "CN")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// true
// false
}
```
### <span id="IsChineseHMPassport">IsChineseHMPassport</span>
<p>判断港澳台通行证(正则判断)。</p>
<b>函数签名:</b>
```go
func IsChineseHMPassport(hmPassport string) bool
```
<b>示例:<span style="float:right;display:inline-block">[运行](https://go.dev/play/p/todo)</span></b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsChineseHMPassport("C12345678")
result2 := validator.IsChineseHMPassport("C00000000")
result3 := validator.IsChineseHMPassport("M12345678")
result4 := validator.IsChineseHMPassport("c12345678")
result5 := validator.IsChineseHMPassport("C1234567")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// false
// false
}
```
+1
View File
@@ -46,6 +46,7 @@ outline: deep
<div class="package-cell">cryptor</div> <div class="package-cell">cryptor</div>
<div class="package-cell">datastructure</div> <div class="package-cell">datastructure</div>
<div class="package-cell">datetime</div> <div class="package-cell">datetime</div>
<div class="package-cell">enum</div>
<div class="package-cell">eventbus</div> <div class="package-cell">eventbus</div>
<div class="package-cell">fileutil</div> <div class="package-cell">fileutil</div>
<div class="package-cell">formatter</div> <div class="package-cell">formatter</div>
+850
View File
@@ -0,0 +1,850 @@
# Enum
Package enum provides a simple enum implementation.
<div STYLE="page-break-after: always;"></div>
## Source:
- [https://github.com/duke-git/lancet/blob/main/enum/enum.go](https://github.com/duke-git/lancet/blob/main/enum/enum.go)
<div STYLE="page-break-after: always;"></div>
## Usage:
```go
import (
"github.com/duke-git/lancet/v2/enum"
)
```
<div STYLE="page-break-after: always;"></div>
## Index
- [NewItem](#NewItem)
- [NewItemsFromPairs](#NewItemsFromPairs)
- [Value](#Value)
- [Name](#Name)
- [Valid](#Valid)
- [MarshalJSON](#MarshalJSON)
- [NewRegistry](#NewRegistry)
- [Add](#Add)
- [Remove](#Remove)
- [Update](#Update)
- [GetByValue](#GetByValue)
- [GetByName](#GetByName)
- [Items](#Items)
- [Contains](#Contains)
- [Size](#Size)
- [Range](#Range)
- [SortedItems](#SortedItems)
- [Filter](#Filter)
<div STYLE="page-break-after: always;"></div>
## Documentation
### <span id="NewItem">NewItem</span>
<p>Creates a new enum item.</p>
<b>Signature:</b>
```go
func NewItem[T comparable](value T, name string) *Item[T]
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
fmt.Println(item1.Name(), item1.Value())
fmt.Println(item2.Name(), item2.Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="NewItemsFromPairs">NewItemsFromPairs</span>
<p>Creates enum items from a slice of Pair structs.</p>
<b>Signature:</b>
```go
func NewItemsFromPairs[T comparable](pairs ...Pair[T]) []*Item[T]
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
items := enum.NewItemsFromPairs(
enum.Pair[Status]{Value: Active, Name: "Active"},
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
)
fmt.Println(items[0].Name(), items[0].Value())
fmt.Println(items[1].Name(), items[1].Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Value">Value</span>
<p>Returns the value of the enum item.</p>
<b>Signature:</b>
```go
func (it *Item[T]) Value() T
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
items := enum.NewItemsFromPairs(
enum.Pair[Status]{Value: Active, Name: "Active"},
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
)
fmt.Println(items[0].Name(), items[0].Value())
fmt.Println(items[1].Name(), items[1].Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Name">Name</span>
<p>Returns the name of the enum item.</p>
<b>Signature:</b>
```go
func (it *Item[T]) Name() string
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
items := enum.NewItemsFromPairs(
enum.Pair[Status]{Value: Active, Name: "Active"},
enum.Pair[Status]{Value: Inactive, Name: "Inactive"},
)
fmt.Println(items[0].Name(), items[0].Value())
fmt.Println(items[1].Name(), items[1].Value())
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Valid">Valid</span>
<p>Checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.</p>
<b>Signature:</b>
```go
func (it *Item[T]) Valid(checker ...func(T) bool) bool
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
item := enum.NewItem(Active, "Active")
fmt.Println(item.Valid())
invalidItem := enum.NewItem(Unknown, "")
fmt.Println(invalidItem.Valid())
// Output:
// true
// false
}
```
### <span id="MarshalJSON">MarshalJSON</span>
<p>Implementation of json.Marshaler interface.</p>
<b>Signature:</b>
```go
func (it *Item[T]) MarshalJSON() ([]byte, error)
func (it *Item[T]) UnmarshalJSON(data []byte) error
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
item := enum.NewItem(Active, "Active")
data, _ := item.MarshalJSON()
fmt.Println(string(data))
var unmarshaledItem Item[Status]
_ = unmarshaledItem.UnmarshalJSON(data)
fmt.Println(unmarshaledItem.Name(), unmarshaledItem.Value())
// Output:
// {"name":"Active","value":1}
// Active 1
}
```
### <span id="NewRegistry">NewRegistry</span>
<p>Creates a new enum registry.</p>
<b>Signature:</b>
```go
func NewRegistry[T comparable](items ...*Item[T]) *Registry[T]
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
if item, found := registry.GetByValue(Active); found {
fmt.Println("Found by value:", item.Name())
}
if item, found := registry.GetByName("Inactive"); found {
fmt.Println("Found by name:", item.Value())
}
// Output:
// Found by value: Active
// Found by name: 2
}
```
### <span id="Add">Add</span>
<p>Adds enum items to the registry.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Add(items ...*Item[T])
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
if item, found := registry.GetByValue(Active); found {
fmt.Println("Found by value:", item.Name())
}
if item, found := registry.GetByName("Inactive"); found {
fmt.Println("Found by name:", item.Value())
}
// Output:
// Found by value: Active
// Found by name: 2
}
```
### <span id="Remove">Remove</span>
<p>Removes an enum item from the registry by its value.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Remove(value T) bool
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
registry.Add(item1)
fmt.Println("Size before removal:", registry.Size())
removed := registry.Remove(Active)
fmt.Println("Removed:", removed)
fmt.Println("Size after removal:", registry.Size())
// Output:
// Size before removal: 1
// Removed: true
// Size after removal: 0
}
```
### <span id="Update">Update</span>
<p>Updates the name of an enum item in the registry by its value.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Update(value T, newName string) bool
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
registry.Add(item1)
updated := registry.Update(Active, "Activated")
fmt.Println("Updated:", updated)
if item, found := registry.GetByValue(Active); found {
fmt.Println("New name:", item.Name())
}
// Output:
// Updated: true
// New name: Activated
}
```
### <span id="GetByValue">GetByValue</span>
<p>Retrieves an enum item by its value.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) GetByValue(value T) (*Item[T], bool)
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
registry.Add(item1, item2)
if item, found := registry.GetByValue(Active); found {
fmt.Println("Found name by value:", item.Name())
}
// Output:
// Found name by value: Active
}
```
### <span id="GetByName">GetByName</span>
<p>Retrieves an enum item by its name.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) GetByName(name string) (*Item[T], bool)
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item := enum.NewItem(Active, "Active")
registry.Add(item)
if item, found := registry.GetByName("Active"); found {
fmt.Println("Found value by name:", item.Value())
}
// Output:
// Found value by name: 1
}
```
### <span id="Items">Items</span>
<p>Returns a slice of all enum items in the registry.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Items() []*Item[T]
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
for _, item := range registry.Items() {
fmt.Println(item.Name(), item.Value())
}
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Contains">Contains</span>
<p>Checks if an enum item with the given value exists in the registry.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Contains(value T) bool
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item := enum.NewItem(Active, "Active")
registry.Add(item)
fmt.Println(registry.Contains(Active))
fmt.Println(registry.Contains(Inactive))
// Output:
// true
// false
}
```
### <span id="Size">Size</span>
<p>Returns the number of enum items in the registry.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Size() int
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
fmt.Println("Initial size:", registry.Size())
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
fmt.Println("Size after adding items:", registry.Size())
registry.Remove(Active)
fmt.Println("Size after removing an item:", registry.Size())
// Output:
// Initial size: 0
// Size after adding items: 2
// Size after removing an item: 1
}
```
### <span id="Range">Range</span>
<p>Iterates over all enum items in the registry and applies the given function.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Range(fn func(*Item[T]) bool)
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
registry.Range(func(item *Item[Status]) bool {
fmt.Println(item.Name(), item.Value())
return true // continue iteration
})
// Output:
// Active 1
// Inactive 2
}
```
### <span id="SortedItems">SortedItems</span>
<p>Returns a slice of all enum items sorted by the given less function.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) SortedItems(less func(*Item[T], *Item[T]) bool) []*Item[T]
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Inactive, "Inactive")
item2 := enum.NewItem(Active, "Active")
registry.Add(item1, item2)
for _, item := range registry.SortedItems(func(i1, i2 *Item[Status]) bool {
return i1.value < i2.value
}) {
fmt.Println(item.Name(), item.Value())
}
// Output:
// Active 1
// Inactive 2
}
```
### <span id="Filter">Filter</span>
<p>Returns a slice of enum items that satisfy the given predicate function.</p>
<b>Signature:</b>
```go
func (r *Registry[T]) Filter(predicate func(*Item[T]) bool) []*Item[T]
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/enum"
)
type Status int
const (
Unknown Status = iota
Active
Inactive
)
func main() {
registry := enum.NewRegistry[Status]()
item1 := enum.NewItem(Active, "Active")
item2 := enum.NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
activeItems := registry.Filter(func(item *Item[Status]) bool {
return item.Value() == Active
})
for _, item := range activeItems {
fmt.Println(item.Name(), item.Value())
}
// Output:
// Active 1
}
```
+68
View File
@@ -79,6 +79,8 @@ import (
- [SortByKey](#SortByKey) - [SortByKey](#SortByKey)
- [GetOrDefault](#GetOrDefault) - [GetOrDefault](#GetOrDefault)
- [FindValuesBy](#FindValuesBy) - [FindValuesBy](#FindValuesBy)
- [ToMarkdownTable](#ToMarkdownTable)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
@@ -2363,3 +2365,69 @@ func main() {
// [b d] // [b d]
} }
``` ```
### <span id="ToMarkdownTable">ToMarkdownTable</span>
<p>Convert a map slice data to a Markdown table string. It supports custom header display names and column display order.</p>
<b>Signature:</b>
```go
编辑
func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/maputil"
)
func main() {
// basic usage: automatically extract column names from data as table headers
data := []map[string]interface{}{
{"name": "Alice", "age": 25, "salary": 50000},
{"name": "Bob", "age": 30, "salary": 60000},
}
result := maputil.ToMarkdownTable(data, nil, nil)
fmt.Println(result)
// output:
// |name|age|salary|
// |---|---|---|
// |Alice|25|50000|
// |Bob|30|60000|
// custom header name
headerMap := map[string]string{
"name": "n",
"age": "a",
"salary": "s",
}
result = maputil.ToMarkdownTable(data, headerMap, nil)
fmt.Println(result)
// ouput:
// |m|a|s|
// |---|---|---|
// |Alice|25|50000|
// |Bob|30|60000|
// custom column display order
columnOrder := []string{"salary", "name"}
result = maputil.ToMarkdownTable(data, nil, columnOrder)
fmt.Println(result)
// 输出:
// |salary|name|
// |---|---|
// |50000|Alice|
// |60000|Bob|
}
```
+61 -17
View File
@@ -31,6 +31,7 @@ import (
- [IsStruct](#IsStruct) - [IsStruct](#IsStruct)
- [Tag](#Tag) - [Tag](#Tag)
- [Name](#Name) - [Name](#Name)
- [TypeName](#TypeName)
- [Value](#Value) - [Value](#Value)
- [Kind](#Kind) - [Kind](#Kind)
- [IsEmbedded](#IsEmbedded) - [IsEmbedded](#IsEmbedded)
@@ -53,12 +54,13 @@ import (
func New(value any, tagName ...string) *Struct func New(value any, tagName ...string) *Struct
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/O29l8kk-Z17)</span></b>
```go ```go
package main package main
import ( import (
"fmt"
"github.com/duke-git/lancet/v2/structs" "github.com/duke-git/lancet/v2/structs"
) )
@@ -68,7 +70,11 @@ func main() {
} }
p1 := &People{Name: "11"} p1 := &People{Name: "11"}
s := structs.New(p1) s := structs.New(p1)
// to do something
fmt.Println(s.ToMap())
// Output:
// map[name:11] <nil>
} }
``` ```
@@ -88,7 +94,7 @@ func (s *Struct) ToMap() (map[string]any, error)
func ToMap(v any) (map[string]any, error) func ToMap(v any) (map[string]any, error)
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/qQbLySBgerZ)</span></b>
```go ```go
package main package main
@@ -130,7 +136,7 @@ func main() {
func (s *Struct) Fields() []*Field func (s *Struct) Fields() []*Field
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/w3Kk_CyVY7D)</span></b>
```go ```go
package main package main
@@ -162,10 +168,10 @@ func main() {
<b>Signature:</b> <b>Signature:</b>
```go ```go
func (s *Struct) Field(name string) *Field func (s *Struct) Field(name string) (*Field, bool)
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/KocZMSYarza)</span></b>
```go ```go
package main package main
@@ -181,12 +187,14 @@ func main() {
} }
p1 := &People{Name: "11"} p1 := &People{Name: "11"}
s := structs.New(p1) s := structs.New(p1)
f := s.Field("Name") f, found := s.Field("Name")
fmt.Println(f.Value()) fmt.Println(f.Value())
fmt.Println(found)
// Output: // Output:
// 11 // 11
// true
} }
``` ```
@@ -200,7 +208,7 @@ func main() {
func (s *Struct) IsStruct() bool func (s *Struct) IsStruct() bool
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/bU2FSdkbK1C)</span></b>
```go ```go
package main package main
@@ -234,7 +242,7 @@ func main() {
func (f *Field) Tag() *Tag func (f *Field) Tag() *Tag
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/DVrx5HvvUJr)</span></b>
```go ```go
package main package main
@@ -271,7 +279,7 @@ func main() {
func (f *Field) Value() any func (f *Field) Value() any
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/qufYEU2o4Oi)</span></b>
```go ```go
package main package main
@@ -307,7 +315,7 @@ func main() {
func (f *Field) IsEmbedded() bool func (f *Field) IsEmbedded() bool
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/wV2PrbYm3Ec)</span></b>
```go ```go
package main package main
@@ -352,7 +360,7 @@ func main() {
func (f *Field) IsExported() bool func (f *Field) IsExported() bool
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/csK4AXYaNbJ)</span></b>
```go ```go
package main package main
@@ -391,7 +399,7 @@ func main() {
func (f *Field) IsZero() bool func (f *Field) IsZero() bool
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/RzqpGISf87r)</span></b>
```go ```go
package main package main
@@ -430,7 +438,7 @@ func main() {
func (f *Field) Name() string func (f *Field) Name() string
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/zfIGlqsatee)</span></b>
```go ```go
package main package main
@@ -469,7 +477,7 @@ func main() {
func (f *Field) Kind() reflect.Kind func (f *Field) Kind() reflect.Kind
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/wg4NlcUNG5o)</span></b>
```go ```go
package main package main
@@ -498,6 +506,42 @@ func main() {
} }
``` ```
### <span id="TypeName">TypeName</span>
<p>Return struct type name.</p>
<b>Signature:</b>
```go
func (s *Struct) TypeName() string
```
<b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/todo)</span></b>
```go
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/structs"
)
func main() {
type Parent struct {
Name string
Age int
}
p := &Parent{Age: 11}
s := structs.New(p1)
fmt.Println(s.TypeName())
// Output:
// Parent
}
```
### <span id="IsSlice">IsSlice</span> ### <span id="IsSlice">IsSlice</span>
<p>Check if the field is a slice</p> <p>Check if the field is a slice</p>
@@ -508,7 +552,7 @@ func main() {
func (f *Field) IsSlice() bool func (f *Field) IsSlice() bool
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/MKz4CgBIUrU)</span></b>
```go ```go
package main package main
@@ -545,7 +589,7 @@ func main() {
func (f *Field) IsTargetType(targetType reflect.Kind) bool func (f *Field) IsTargetType(targetType reflect.Kind) bool
``` ```
<b>Example:</b> <b>Example:<span style="float:right;display:inline-block;">[Run](https://go.dev/play/p/Ig75P-agN39)</span></b>
```go ```go
package main package main
+79
View File
@@ -65,6 +65,8 @@ import (
- [IsAmericanExpress](#IsAmericanExpress) - [IsAmericanExpress](#IsAmericanExpress)
- [IsUnionPay](#IsUnionPay) - [IsUnionPay](#IsUnionPay)
- [IsChinaUnionPay](#IsChinaUnionPay) - [IsChinaUnionPay](#IsChinaUnionPay)
- [IsPassport](#IsPassport)
- [IsChineseHMPassport](#IsChineseHMPassport)
<div STYLE="page-break-after: always;"></div> <div STYLE="page-break-after: always;"></div>
@@ -1569,3 +1571,80 @@ func main() {
// false // false
} }
``` ```
### <span id="IsPassport">IsPassport</span>
<p>Passport validation(using regex).</p>
<b>Signature:</b>
```go
func IsPassport(passport, country string) bool
```
<b>Example:<span style="float:right;display:inline-block">[Run](https://go.dev/play/p/todo)</span></b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsPassport("P123456789", "CN")
result2 := validator.IsPassport("123456789", "US")
result3 := validator.IsPassport("AB1234567", "RU")
result4 := validator.IsPassport("123456789", "CN")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
// Output:
// true
// true
// true
// false
}
```
### <span id="IsChineseHMPassport">IsChineseHMPassport</span>
<p>Mainland travel permit for Hong Kong, Macao validation (using regex). </p>
<b>Signature:</b>
```go
func IsChineseHMPassport(hmPassport string) bool
```
<b>Example:<span style="float:right;display:inline-block">[Run](https://go.dev/play/p/todo)</span></b>
```go
import (
"fmt"
"github.com/duke-git/lancet/v2/validator"
)
func main() {
result1 := validator.IsChineseHMPassport("C12345678")
result2 := validator.IsChineseHMPassport("C00000000")
result3 := validator.IsChineseHMPassport("M12345678")
result4 := validator.IsChineseHMPassport("c12345678")
result5 := validator.IsChineseHMPassport("C1234567")
fmt.Println(result1)
fmt.Println(result2)
fmt.Println(result3)
fmt.Println(result4)
fmt.Println(result5)
// Output:
// true
// true
// true
// false
// false
}
```
+334 -192
View File
File diff suppressed because it is too large Load Diff
+27 -41
View File
@@ -26,6 +26,7 @@ type Item[T comparable] struct {
name string name string
} }
// NewItem creates a new enum item.
func NewItem[T comparable](value T, name string) *Item[T] { func NewItem[T comparable](value T, name string) *Item[T] {
return &Item[T]{value: value, name: name} return &Item[T]{value: value, name: name}
} }
@@ -37,7 +38,7 @@ type Pair[T comparable] struct {
} }
// NewItemsFromPairs creates enum items from a slice of Pair structs. // NewItemsFromPairs creates enum items from a slice of Pair structs.
func NewItems[T comparable](pairs ...Pair[T]) []*Item[T] { func NewItemsFromPairs[T comparable](pairs ...Pair[T]) []*Item[T] {
if len(pairs) == 0 { if len(pairs) == 0 {
return []*Item[T]{} return []*Item[T]{}
} }
@@ -50,37 +51,40 @@ func NewItems[T comparable](pairs ...Pair[T]) []*Item[T] {
return items return items
} }
func (e *Item[T]) Value() T { // Value returns the value of the enum item.
return e.value func (it *Item[T]) Value() T {
return it.value
} }
func (e *Item[T]) Name() string { // Name returns the name of the enum item.
return e.name func (it *Item[T]) Name() string {
return it.name
} }
func (e *Item[T]) String() string { // String returns the string representation of the enum item.
return e.name func (it *Item[T]) String() string {
return it.name
} }
// Valid checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value. // Valid checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.
func (e *Item[T]) Valid(checker ...func(T) bool) bool { func (it *Item[T]) Valid(checker ...func(T) bool) bool {
if len(checker) > 0 { if len(checker) > 0 {
return checker[0](e.value) && e.name != "" return checker[0](it.value) && it.name != ""
} }
var zero T var zero T
return e.value != zero && e.name != "" return it.value != zero && it.name != ""
} }
// MarshalJSON implements the json.Marshaler interface. // MarshalJSON implements the json.Marshaler interface.
func (e *Item[T]) MarshalJSON() ([]byte, error) { func (it *Item[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]any{ return json.Marshal(map[string]any{
"value": e.value, "value": it.value,
"name": e.name, "name": it.name,
}) })
} }
// UnmarshalJSON implements the json.Unmarshaler interface. // UnmarshalJSON implements the json.Unmarshaler interface.
func (e *Item[T]) UnmarshalJSON(data []byte) error { func (it *Item[T]) UnmarshalJSON(data []byte) error {
type alias struct { type alias struct {
Value any `json:"value"` Value any `json:"value"`
Name string `json:"name"` Name string `json:"name"`
@@ -99,48 +103,47 @@ func (e *Item[T]) UnmarshalJSON(data []byte) error {
return fmt.Errorf("invalid type for value, want int family") return fmt.Errorf("invalid type for value, want int family")
} }
converted := reflect.ValueOf(int64(val)).Convert(rv) converted := reflect.ValueOf(int64(val)).Convert(rv)
e.value = converted.Interface().(T) it.value = converted.Interface().(T)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
val, ok := temp.Value.(float64) val, ok := temp.Value.(float64)
if !ok { if !ok {
return fmt.Errorf("invalid type for value, want uint family") return fmt.Errorf("invalid type for value, want uint family")
} }
converted := reflect.ValueOf(uint64(val)).Convert(rv) converted := reflect.ValueOf(uint64(val)).Convert(rv)
e.value = converted.Interface().(T) it.value = converted.Interface().(T)
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
val, ok := temp.Value.(float64) val, ok := temp.Value.(float64)
if !ok { if !ok {
return fmt.Errorf("invalid type for value, want float family") return fmt.Errorf("invalid type for value, want float family")
} }
converted := reflect.ValueOf(val).Convert(rv) converted := reflect.ValueOf(val).Convert(rv)
e.value = converted.Interface().(T) it.value = converted.Interface().(T)
case reflect.String: case reflect.String:
val, ok := temp.Value.(string) val, ok := temp.Value.(string)
if !ok { if !ok {
return fmt.Errorf("invalid type for value, want string") return fmt.Errorf("invalid type for value, want string")
} }
e.value = any(val).(T) it.value = any(val).(T)
case reflect.Bool: case reflect.Bool:
val, ok := temp.Value.(bool) val, ok := temp.Value.(bool)
if !ok { if !ok {
return fmt.Errorf("invalid type for value, want bool") return fmt.Errorf("invalid type for value, want bool")
} }
e.value = any(val).(T) it.value = any(val).(T)
default: default:
// 枚举类型底层通常是 int,可以尝试 float64->int64->底层类型
val, ok := temp.Value.(float64) val, ok := temp.Value.(float64)
if ok { if ok {
converted := reflect.ValueOf(int64(val)).Convert(rv) converted := reflect.ValueOf(int64(val)).Convert(rv)
e.value = converted.Interface().(T) it.value = converted.Interface().(T)
} else { } else {
val2, ok2 := temp.Value.(T) val2, ok2 := temp.Value.(T)
if !ok2 { if !ok2 {
return fmt.Errorf("invalid type for value") return fmt.Errorf("invalid type for value")
} }
e.value = val2 it.value = val2
} }
} }
e.name = temp.Name it.name = temp.Name
return nil return nil
} }
@@ -152,6 +155,7 @@ type Registry[T comparable] struct {
items []*Item[T] items []*Item[T]
} }
// NewRegistry creates a new enum registry.
func NewRegistry[T comparable](items ...*Item[T]) *Registry[T] { func NewRegistry[T comparable](items ...*Item[T]) *Registry[T] {
r := &Registry[T]{ r := &Registry[T]{
values: make(map[T]*Item[T]), values: make(map[T]*Item[T]),
@@ -250,24 +254,6 @@ func (r *Registry[T]) Contains(value T) bool {
return ok return ok
} }
// Validate checks if the given value is a valid enum item in the registry.
func (r *Registry[T]) Validate(value T) error {
if !r.Contains(value) {
return fmt.Errorf("invalid enum value: %v", value)
}
return nil
}
// ValidateAll checks if all given values are valid enum items in the registry.
func (r *Registry[T]) ValidateAll(values ...T) error {
for _, value := range values {
if err := r.Validate(value); err != nil {
return err
}
}
return nil
}
// Size returns the number of enum items in the registry. // Size returns the number of enum items in the registry.
func (r *Registry[T]) Size() int { func (r *Registry[T]) Size() int {
r.mu.RLock() r.mu.RLock()
+19 -33
View File
@@ -3,7 +3,19 @@ package enum
import "fmt" import "fmt"
func ExampleNewItem() { func ExampleNewItem() {
items := NewItems( item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
fmt.Println(item1.Name(), item1.Value())
fmt.Println(item2.Name(), item2.Value())
// Output:
// Active 1
// Inactive 2
}
func ExampleNewItemsFromPairs() {
items := NewItemsFromPairs(
Pair[Status]{Value: Active, Name: "Active"}, Pair[Status]{Value: Active, Name: "Active"},
Pair[Status]{Value: Inactive, Name: "Inactive"}, Pair[Status]{Value: Inactive, Name: "Inactive"},
) )
@@ -114,41 +126,15 @@ func ExampleRegistry_Items() {
func ExampleRegistry_Contains() { func ExampleRegistry_Contains() {
registry := NewRegistry[Status]() registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active") item := NewItem(Active, "Active")
registry.Add(item1) registry.Add(item)
fmt.Println("Contains Active:", registry.Contains(Active)) fmt.Println(registry.Contains(Active))
fmt.Println("Contains Inactive:", registry.Contains(Inactive)) fmt.Println(registry.Contains(Inactive))
}
func ExampleRegistry_Validate() {
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
fmt.Println("Validate Active:", registry.Validate(Active))
fmt.Println("Validate Inactive:", registry.Validate(Inactive))
fmt.Println("Validate Unknown:", registry.Validate(Unknown))
// Output: // Output:
// Validate Active: <nil> // true
// Validate Inactive: <nil> // false
// Validate Unknown: invalid enum value: 0
}
func ExampleRegistry_ValidateAll() {
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
fmt.Println("ValidateAll Active, Inactive:", registry.ValidateAll(Active, Inactive))
fmt.Println("ValidateAll Active, Unknown:", registry.ValidateAll(Active, Unknown))
// Output:
// ValidateAll Active, Inactive: <nil>
// ValidateAll Active, Unknown: invalid enum value: 0
} }
func ExampleRegistry_Size() { func ExampleRegistry_Size() {
+3 -37
View File
@@ -17,11 +17,11 @@ const (
Inactive Inactive
) )
func TestNewItem(t *testing.T) { func TestNewItemsFromPairs(t *testing.T) {
t.Parallel() t.Parallel()
assert := internal.NewAssert(t, "TestNewItem") assert := internal.NewAssert(t, "TestNewItemsFromPairs")
items := NewItems( items := NewItemsFromPairs(
Pair[Status]{Value: Active, Name: "Active"}, Pair[Status]{Value: Active, Name: "Active"},
Pair[Status]{Value: Inactive, Name: "Inactive"}, Pair[Status]{Value: Inactive, Name: "Inactive"},
) )
@@ -128,40 +128,6 @@ func TestRegistry_Contains(t *testing.T) {
assert.Equal(false, registry.Contains(Inactive)) assert.Equal(false, registry.Contains(Inactive))
} }
func TestRegistry_Validate(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRegistry_Validate")
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
err := registry.Validate(Active)
assert.IsNil(err)
err = registry.Validate(Inactive)
assert.IsNil(err)
err = registry.Validate(Unknown)
assert.IsNotNil(err)
}
func TestRegistry_ValidateAll(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestRegistry_ValidateAll")
registry := NewRegistry[Status]()
item1 := NewItem(Active, "Active")
item2 := NewItem(Inactive, "Inactive")
registry.Add(item1, item2)
err := registry.ValidateAll(Active, Inactive)
assert.IsNil(err)
err = registry.ValidateAll(Active, Unknown)
assert.IsNotNil(err)
}
func TestRegistry_Range(t *testing.T) { func TestRegistry_Range(t *testing.T) {
t.Parallel() t.Parallel()
assert := internal.NewAssert(t, "TestRegistry_Range") assert := internal.NewAssert(t, "TestRegistry_Range")
+1
View File
@@ -683,6 +683,7 @@ func FindValuesBy[K comparable, V any](m map[K]V, predicate func(key K, value V)
} }
// ToMarkdownTable converts a slice of maps to a Markdown table. // ToMarkdownTable converts a slice of maps to a Markdown table.
// Play: ttps://go.dev/play/p/todo
func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string { func ToMarkdownTable(data []map[string]interface{}, headerMap map[string]string, columnOrder []string) string {
if len(data) == 0 { if len(data) == 0 {
return "| |\n|---|\n" return "| |\n|---|\n"
+9
View File
@@ -26,26 +26,31 @@ func newField(v reflect.Value, f reflect.StructField, tagName string) *Field {
} }
// Tag returns the value that the key in the tag string. // Tag returns the value that the key in the tag string.
// Play: https://go.dev/play/p/DVrx5HvvUJr
func (f *Field) Tag() *Tag { func (f *Field) Tag() *Tag {
return f.tag return f.tag
} }
// Value returns the underlying value of the field. // Value returns the underlying value of the field.
// Play: https://go.dev/play/p/qufYEU2o4Oi
func (f *Field) Value() any { func (f *Field) Value() any {
return f.rvalue.Interface() return f.rvalue.Interface()
} }
// IsEmbedded returns true if the given field is an embedded field. // IsEmbedded returns true if the given field is an embedded field.
// Play: https://go.dev/play/p/wV2PrbYm3Ec
func (f *Field) IsEmbedded() bool { func (f *Field) IsEmbedded() bool {
return len(f.field.Index) > 1 return len(f.field.Index) > 1
} }
// IsExported returns true if the given field is exported. // IsExported returns true if the given field is exported.
// Play: https://go.dev/play/p/csK4AXYaNbJ
func (f *Field) IsExported() bool { func (f *Field) IsExported() bool {
return f.field.IsExported() return f.field.IsExported()
} }
// IsZero returns true if the given field is zero value. // IsZero returns true if the given field is zero value.
// Play: https://go.dev/play/p/RzqpGISf87r
func (f *Field) IsZero() bool { func (f *Field) IsZero() bool {
z := reflect.Zero(f.rvalue.Type()).Interface() z := reflect.Zero(f.rvalue.Type()).Interface()
v := f.Value() v := f.Value()
@@ -63,22 +68,26 @@ func (f *Field) IsNil() bool {
} }
// Name returns the name of the given field // Name returns the name of the given field
// Play: https://go.dev/play/p/zfIGlqsatee
func (f *Field) Name() string { func (f *Field) Name() string {
return f.field.Name return f.field.Name
} }
// Kind returns the field's kind // Kind returns the field's kind
// Play: https://go.dev/play/p/wg4NlcUNG5o
func (f *Field) Kind() reflect.Kind { func (f *Field) Kind() reflect.Kind {
return f.rvalue.Kind() return f.rvalue.Kind()
} }
// IsSlice check if a struct field type is slice or not // IsSlice check if a struct field type is slice or not
// Play: https://go.dev/play/p/MKz4CgBIUrU
func (f *Field) IsSlice() bool { func (f *Field) IsSlice() bool {
k := f.rvalue.Kind() k := f.rvalue.Kind()
return k == reflect.Slice return k == reflect.Slice
} }
// IsTargetType check if a struct field type is target type or not // IsTargetType check if a struct field type is target type or not
// Play: https://go.dev/play/p/Ig75P-agN39
func (f *Field) IsTargetType(targetType reflect.Kind) bool { func (f *Field) IsTargetType(targetType reflect.Kind) bool {
return f.rvalue.Kind() == targetType return f.rvalue.Kind() == targetType
} }
+7
View File
@@ -20,6 +20,7 @@ type Struct struct {
} }
// New returns a new *Struct // New returns a new *Struct
// Play: https://go.dev/play/p/O29l8kk-Z17
func New(value any, tagName ...string) *Struct { func New(value any, tagName ...string) *Struct {
value = pointer.ExtractPointer(value) value = pointer.ExtractPointer(value)
v := reflect.ValueOf(value) v := reflect.ValueOf(value)
@@ -60,6 +61,7 @@ func New(value any, tagName ...string) *Struct {
// Name string `json:"myName"` // Name string `json:"myName"`
// //
// ToMap convert the exported fields of a struct to map. // ToMap convert the exported fields of a struct to map.
// Play: https://go.dev/play/p/qQbLySBgerZ
func (s *Struct) ToMap() (map[string]any, error) { func (s *Struct) ToMap() (map[string]any, error) {
if !s.IsStruct() { if !s.IsStruct() {
return nil, fmt.Errorf("invalid struct %v", s) return nil, fmt.Errorf("invalid struct %v", s)
@@ -87,6 +89,7 @@ func (s *Struct) ToMap() (map[string]any, error) {
} }
// Fields returns all the struct fields within a slice // Fields returns all the struct fields within a slice
// Play: https://go.dev/play/p/w3Kk_CyVY7D
func (s *Struct) Fields() []*Field { func (s *Struct) Fields() []*Field {
fieldNum := s.rvalue.NumField() fieldNum := s.rvalue.NumField()
fields := make([]*Field, 0, fieldNum) fields := make([]*Field, 0, fieldNum)
@@ -100,6 +103,7 @@ func (s *Struct) Fields() []*Field {
} }
// Field returns a Field if the given field name was found // Field returns a Field if the given field name was found
// Play: https://go.dev/play/p/KocZMSYarza
func (s *Struct) Field(name string) (*Field, bool) { func (s *Struct) Field(name string) (*Field, bool) {
f, ok := s.rtype.FieldByName(name) f, ok := s.rtype.FieldByName(name)
if !ok { if !ok {
@@ -109,6 +113,7 @@ func (s *Struct) Field(name string) (*Field, bool) {
} }
// IsStruct returns true if the given rvalue is a struct // IsStruct returns true if the given rvalue is a struct
// Play: https://go.dev/play/p/bU2FSdkbK1C
func (s *Struct) IsStruct() bool { func (s *Struct) IsStruct() bool {
k := s.rvalue.Kind() k := s.rvalue.Kind()
if k == reflect.Invalid { if k == reflect.Invalid {
@@ -119,11 +124,13 @@ func (s *Struct) IsStruct() bool {
// ToMap convert struct to map, only convert exported struct field // ToMap convert struct to map, only convert exported struct field
// map key is specified same as struct field tag `json` value. // map key is specified same as struct field tag `json` value.
// Play: https://go.dev/play/p/qQbLySBgerZ
func ToMap(v any) (map[string]any, error) { func ToMap(v any) (map[string]any, error) {
return New(v).ToMap() return New(v).ToMap()
} }
// TypeName return struct type name // TypeName return struct type name
// Play: https://go.dev/play/p/todo
func (s *Struct) TypeName() string { func (s *Struct) TypeName() string {
return s.rtype.Name() return s.rtype.Name()
} }
+2 -23
View File
@@ -24,10 +24,8 @@ var (
alphaNumericMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z0-9-]+$`) alphaNumericMatcher *regexp.Regexp = regexp.MustCompile(`^[a-zA-Z0-9-]+$`)
numberRegexMatcher *regexp.Regexp = regexp.MustCompile(`\d`) numberRegexMatcher *regexp.Regexp = regexp.MustCompile(`\d`)
intStrMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`) intStrMatcher *regexp.Regexp = regexp.MustCompile(`^[\+-]?\d+$`)
urlMatcher *regexp.Regexp = regexp.MustCompile(`^((ftp|http|https?):\/\/)?(\S+(:\S*)?@)?((([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(([a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)*)|((www\.)?))?(([a-z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-z\x{00a1}-\x{ffff}]{2,}))?))(:(\d{1,5}))?((\/|\?|#)[^\s]*)?$`) // dnsMatcher *regexp.Regexp = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
dnsMatcher *regexp.Regexp = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`) dnsMatcher *regexp.Regexp = regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*(?:xn--[a-zA-Z0-9\-]{1,59}|[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)$`)
// emailMatcher *regexp.Regexp = regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
emailMatcher *regexp.Regexp = regexp.MustCompile(`\w+(-+.\w+)*@\w+(-.\w+)*.\w+(-.\w+)*`)
chineseMobileMatcher *regexp.Regexp = regexp.MustCompile(`^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$`) chineseMobileMatcher *regexp.Regexp = regexp.MustCompile(`^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$`)
chineseIdMatcher *regexp.Regexp = regexp.MustCompile(`([1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx])|([1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx])`) chineseIdMatcher *regexp.Regexp = regexp.MustCompile(`([1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx])|([1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx])`)
chineseMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]") chineseMatcher *regexp.Regexp = regexp.MustCompile("[\u4e00-\u9fa5]")
@@ -40,7 +38,6 @@ var (
visaMatcher *regexp.Regexp = regexp.MustCompile(`^4[0-9]{12}(?:[0-9]{3})?$`) visaMatcher *regexp.Regexp = regexp.MustCompile(`^4[0-9]{12}(?:[0-9]{3})?$`)
masterCardMatcher *regexp.Regexp = regexp.MustCompile(`^5[1-5][0-9]{14}$`) masterCardMatcher *regexp.Regexp = regexp.MustCompile(`^5[1-5][0-9]{14}$`)
americanExpressMatcher *regexp.Regexp = regexp.MustCompile(`^3[47][0-9]{13}$`) americanExpressMatcher *regexp.Regexp = regexp.MustCompile(`^3[47][0-9]{13}$`)
unionPayMatcher *regexp.Regexp = regexp.MustCompile(`^62[0-5]\\d{13,16}$`)
chinaUnionPayMatcher *regexp.Regexp = regexp.MustCompile(`^62[0-9]{14,17}$`) chinaUnionPayMatcher *regexp.Regexp = regexp.MustCompile(`^62[0-9]{14,17}$`)
chineseHMPassportMatcher *regexp.Regexp = regexp.MustCompile(`^[CM]\d{8}$`) chineseHMPassportMatcher *regexp.Regexp = regexp.MustCompile(`^[CM]\d{8}$`)
) )
@@ -635,24 +632,6 @@ func IsChinaUnionPay(cardNo string) bool {
return chinaUnionPayMatcher.MatchString(cardNo) return chinaUnionPayMatcher.MatchString(cardNo)
} }
// luhnCheck checks if the credit card number is valid using the Luhn algorithm.
func luhnCheck(card string) bool {
var sum int
alt := false
for i := len(card) - 1; i >= 0; i-- {
n := int(card[i] - '0')
if alt {
n *= 2
if n > 9 {
n -= 9
}
}
sum += n
alt = !alt
}
return sum%10 == 0
}
// IsPassport checks if the passport number is valid for a given country. // IsPassport checks if the passport number is valid for a given country.
// country is a two-letter country code (ISO 3166-1 alpha-2). // country is a two-letter country code (ISO 3166-1 alpha-2).
// Play: todo // Play: todo
+2 -1
View File
@@ -477,7 +477,8 @@ func TestIsDns(t *testing.T) {
{"abc.com", true}, {"abc.com", true},
{"123.cn", true}, {"123.cn", true},
{"a.b.com", true}, {"a.b.com", true},
{"a.b.c", false}, {"a.b.c", true},
{"www.xn--6qq986b3xl.xn--fiqs8s.com", true},
{"a@b.com", false}, {"a@b.com", false},
{"http://abc.com", false}, {"http://abc.com", false},
} }