Go
语言提供了可通过反射发现的的结构体标签,这些在标准库json/xml
中得到了广泛的使用;
orm
框架也支持了结构体标签,上面那个例子的使用就是因为encoding/json
支持了结构体标签,不过他有自己的标签规则(ORM全称是:Object Relational Mapping(对象关系映射));
像json
、yaml
、gorm
、validate
、mapstructure
、protobuf
这几个库的结构体标签是很常用的,gin
框架就集成了validate
库用来做参数校验;
Go
官方已经帮忙整理了哪些库已经支持了struct tag
,具体这些库中是怎么使用的,大家可以看官方文档https://github.com/golang/go/wiki/Well-known-struct-tags 介绍,写的都很详细,具体场景具体用:
Tag | Documentation |
---|---|
xml | https://godoc.org/encoding/xml |
json | https://godoc.org/encoding/json |
asn1 | https://godoc.org/encoding/asn1 |
reform | https://godoc.org/gopkg.in/reform.v1 |
dynamodb | https://docs.aws.amazon.com/sdk-for-go/api/service/dynamodb/dynamodbattribute/#Marshal |
bigquery | https://godoc.org/cloud.google.com/go/bigquery |
datastore | https://godoc.org/cloud.google.com/go/datastore |
spanner | https://godoc.org/cloud.google.com/go/spanner |
bson | https://godoc.org/labix.org/v2/mgo/bson, https://godoc.org/go.mongodb.org/mongo-driver/bson/bsoncodec |
gorm | https://godoc.org/github.com/jinzhu/gorm |
yaml | https://godoc.org/gopkg.in/yaml.v2 |
toml | https://godoc.org/github.com/pelletier/go-toml |
validate | https://github.com/go-playground/validator |
mapstructure | https://godoc.org/github.com/mitchellh/mapstructure |
parser | https://godoc.org/github.com/alecthomas/participle |
protobuf | https://github.com/golang/protobuf |
db | https://github.com/jmoiron/sqlx |
url | https://github.com/google/go-querystring |
feature | https://github.com/nikolaydubina/go-featureprocessing |
不同的库即使标签不一样,不过都有一个统一的总体规则:
(2)结构体标签可以有多个键值对
(2)键与值要用冒号分隔
(3)值要使用双引号括起来
(4)多个键值对之间要使用一个空格分隔,千万不要使用逗号!
`key1:"value1" key2:"value2" key3:"value3"...` // 键值对用空格分隔
2.2Tag不同库encoding/json规范举例
如果我们想要在一个值中传递多个信息怎么办?不同库中实现的是不一样的,在encoding/json
中,多值使用逗号分隔:
`json:"lon,omitempty"`
2.3Tag不同库gorm规范举例
如果我们想要在一个值中传递多个信息怎么办?不同库中实现的是不一样的,在gorm
中,多值使用分号分隔:
`gorm:"column:id;primaryKey"
2.4go vet main.go命令
现在大家已经知道什么是结构体标签了,规则还是很规范的,但是很容易出错,因为Go语言在编译阶段并不会对其格式做合法键值对的检查,这样我们不小心写错了,就很难被发现,不过我们有go vet
工具做检查,具体使用来看一个例子:
package main
type User struct {
Name string `abc def ghk`
Age uint16 `123: 232`
}
func main() {
}
bad syntax for struct tag pair
告诉我们键值对语法错误,bad syntax for struct tag value
值语法错误;
所以在我们项目中引入go vet
作为CI
检查是很有必要的
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)