golang提取Go结构体字段名称、类型和标签的插件库textra的使用
Golang提取Go结构体字段名称、类型和标签的插件库textra的使用
Textra是一个零依赖、简单快速的结构体标签解析库。它最初是为另一个私有项目构建的,但后来决定开源,因为它可能对其他人有用。
安装
go get github.com/ravsii/textra
基本使用示例
type Tester struct {
NoTags bool
WithTag string `json:"with_tag,omitempty"`
WithTags string `json:"with_tags" sql:"with_tag"`
SqlOnly string `sql:"sql_only"`
}
func main() {
basic := textra.Extract((*Tester)(nil))
for _, field := range basic {
fmt.Println(field)
}
}
输出结果:
NoTags(bool):[]
WithTag(string):[json:"with_tag,omitempty"]
WithTags(string):[json:"with_tags" sql:"with_tag"]
SqlOnly(string):[sql:"sql_only"]
使用功能方法
移除空标签的字段
removed := basic.RemoveEmpty()
for _, field := range removed {
fmt.Println(field)
}
输出结果:
WithTag(string):[json:"with_tag,omitempty"]
WithTags(string):[json:"with_tags" sql:"with_tag"]
SqlOnly(string):[sql:"sql_only"]
只获取特定标签的字段
onlySQL := removed.OnlyTag("sql")
for _, field := range onlySQL {
fmt.Println(field)
}
输出结果:
WithTags(string):sql:"with_tag"
SqlOnly(string):sql:"sql_only"
类型解析示例
Textra还能解析各种类型的字符串表示:
type Types struct {
intType int
intPType *int
byteType byte
bytePType *byte
byteArrType []byte
byteArrPType []*byte
bytePArrPType *[]*byte
runeType rune
runePType *rune
stringType string
stringPType *string
booleanType bool
booleanPType *bool
mapType map[string]string
mapPType map[*string]*string
mapPImportType map[*string]*time.Time
chanType chan int
funcType func() error
funcParamsType func(arg1 int, arg2 string, arg3 map[*string]*time.Time) (int, error)
importType time.Time
pointerType *string
}
func main() {
fields := textra.Extract((*Types)(nil))
for _, field := range fields {
fmt.Println(field.Name, field.Type)
}
}
输出结果:
intType int
intPType *int
byteType uint8
bytePType *uint8
byteArrType []uint8
byteArrPType []*uint8
bytePArrPType *[]*uint8
runeType int32
runePType *int32
stringType string
stringPType *string
booleanType bool
booleanPType *bool
mapType map[string]string
mapPType map[*string]*string
mapPImportType map[*string]*time.Time
chanType chan
funcType func() error
funcParamsType func(int, string, map[*string]*time.Time) int, error
importType time.Time
pointerType *string
Textra的API设计类似于标准库中的time
包,其中链式函数会创建新值而不是修改它们。
更多关于golang提取Go结构体字段名称、类型和标签的插件库textra的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复