Featured image of post Golang.gin 框架 ---- 请求参数验证

Golang.gin 框架 ---- 请求参数验证

结构体

声明结构体 在结构体中添加字段标记来实现验证

举个栗子 🌰:

登录时必须包含 用户名 user 和 密码 password 则声明如下结构体

1
2
3
4
5
// Binding from JSON
type Login struct {
	User     string `form:"user" json:"user" xml:"user"  binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

binding:"required" 声明字段必须含有

绑定数据

gin.Context 中 调用 bind 方法绑定数据 (Must bind, Should bind 都可)

1
2
3
4
5
var json Login
if err := c.ShouldBindJSON(&json); err != nil {
	c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
	return
}

调用

1
2
3
4
if json.User != "manu" || json.Password != "123" {
	c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
	return
}

常用字段标记

Fields

Tag 说明
eqcsfield Field Equals Another Field (relative) 必须等于 struct Other 中 Field 的值 例: binding:“eqcsfield=Other.Field”`
eqfield Field Equals Another Field 必须等于 Field 例: binding:“eqfield=Field”`
fieldcontains NOT DOCUMENTED IN doc.go
fieldexcludes NOT DOCUMENTED IN doc.go
gtcsfield Field Greater Than Another Relative Field 必须大于 struct Other 中 Field 的值 例: binding:“gtcsfield=Other.Field”`
gtecsfield Field Greater Than or Equal To Another Relative Field 必须大于等于 struct Other 中 Field 的值 例:binding:“gtecsfield=Other.Field”`
gtefield Field Greater Than or Equal To Another Field 必须大于等于 Field 的值
gtfield Field Greater Than Another Field 必须大于 Field 的值
ltcsfield Less Than Another Relative Field 必须小于 struct Other 中 Field 的值 例: binding:“ltcsfield=Other.Field”`
ltecsfield Less Than or Equal To Another Relative Field 必须小于等于 struct Other 中 Field 的值 例: binding:“ltecsfield=Other.Field”`
ltefield Less Than or Equal To Another Field 必须小于等于 Field 的值
ltfield Less Than Another Field 必须小于 Field 的值
necsfield Field Does Not Equal Another Field (relative) 必须不等于 struct Other 中 Field 的值 例: binding:“necsfield=Other.Field”`
nefield Field Does Not Equal Another Field 必须不等 Field

Network:

Tag Description
cidr Classless Inter-Domain Routing CIDR
cidrv4 Classless Inter-Domain Routing CIDRv4
cidrv6 Classless Inter-Domain Routing CIDRv6
datauri Data URL
fqdn Full Qualified Domain Name (FQDN)
hostname Hostname RFC 952
hostname_port HostPort
hostname_rfc1123 Hostname RFC 1123
ip Internet Protocol Address IP
ip4_addr Internet Protocol Address IPv4
ip6_addr Internet Protocol Address IPv6
ip_addr Internet Protocol Address IP
ipv4 Internet Protocol Address IPv4
ipv6 Internet Protocol Address IPv6
mac Media Access Control Address MAC
tcp4_addr Transmission Control Protocol Address TCPv4
tcp6_addr Transmission Control Protocol Address TCPv6
tcp_addr Transmission Control Protocol Address TCP
udp4_addr User Datagram Protocol Address UDPv4
udp6_addr User Datagram Protocol Address UDPv6
udp_addr User Datagram Protocol Address UDP
unix_addr Unix domain socket end point Address
uri URI String
url URL String 验证字符串值包含有效的网址
url_encoded URL Encoded
urn_rfc2141 Urn RFC 2141 String

Strings:

Tag Description
alpha Alpha Only
alphanum Alphanumeric
alphanumunicode Alphanumeric Unicode
alphaunicode Alpha Unicode
ascii ASCII
contains Contains
containsany Contains Any
containsrune Contains Rune
lowercase Lowercase
multibyte Multi-Byte Characters
number NOT DOCUMENTED IN doc.go
numeric Numeric
printascii Printable ASCII
startswith Starts With
uppercase Uppercase

Format:

Tag Description
base64 Base64 String
base64url Base64URL String
btc_addr Bitcoin Address
btc_addr_bech32 Bitcoin Bech32 Address (segwit)
datetime Datetime
email E-mail String 验证字符串是 email 格式
eth_addr Ethereum Address
hexadecimal Hexadecimal String
hexcolor Hexcolor String
hsl HSL String
hsla HSLA String
html HTML Tags
html_encoded HTML Encoded
isbn International Standard Book Number
isbn10 International Standard Book Number 10
isbn13 International Standard Book Number 13
json JSON
latitude Latitude
longitude Longitude
rgb RGB String
rgba RGBA String
ssn Social Security Number SSN
uuid Universally Unique Identifier UUID
uuid3 Universally Unique Identifier UUID v3
uuid3_rfc4122 Universally Unique Identifier UUID v3 RFC4122
uuid4 Universally Unique Identifier UUID v4
uuid4_rfc4122 Universally Unique Identifier UUID v4 RFC4122
uuid5 Universally Unique Identifier UUID v5
uuid5_rfc4122 Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122 Universally Unique Identifier UUID RFC4122

Comparisons:

Tag 说明
eq Equals 数字等于 n,或者或者数组、切片、map 的 len 值为 n,即包含的项目数
gt Greater than 数字大于 n,或者或者数组、切片、map 的 len 值大于 n,即包含的项目数大于 n
gte Greater than or equal 数字大于或等于 n,或者或者数组、切片、map 的 len 值大于或等于 n,即包含的项目数大于或等于 n
lt Less Than 数字小于 n,或者或者数组、切片、map 的 len 值小于 n,即包含的项目数小于 n
lte Less Than or Equal 数字小于或等于 n,或者或者数组、切片、map 的 len 值小于或等于 n,即包含的项目数小于或等于 n
ne Not Equal 数字不等于 n,或者或者数组、切片、map 的 len 值不等于为 n,即包含的项目数不为 n,其和 eq 相反

Other:

Tag Description
dir Directory
e164 NOT DOCUMENTED IN doc.go
endswith Ends With
excludes Excludes
excludesall Excludes All 不能包含特殊字符, 注意用十六进制表示 例: binding:“excludesall=0x2C”`
excludesrune Excludes Rune
file File path
isdefault Is Default
len Length 字符长度必须等于 n,或者数组、切片、map 的 len 值为 n,即包含的项目数
max Maximum 字符串最大长度
min Minimum 字符串最小长度
oneof One Of
required Required 必须
required_with Required With
required_with_all Required With All
required_without Required Without
required_without_all Required Without All
unique Unique

后记

官方验证事例 看这里

gin中内置 数据验证库文档 看这里