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说明
eqcsfieldField Equals Another Field (relative) 必须等于 struct Other 中 Field 的值 例: binding:“eqcsfield=Other.Field”`
eqfieldField Equals Another Field 必须等于 Field 例: binding:“eqfield=Field”`
fieldcontainsNOT DOCUMENTED IN doc.go
fieldexcludesNOT DOCUMENTED IN doc.go
gtcsfieldField Greater Than Another Relative Field 必须大于 struct Other 中 Field 的值 例: binding:“gtcsfield=Other.Field”`
gtecsfieldField Greater Than or Equal To Another Relative Field 必须大于等于 struct Other 中 Field 的值 例:binding:“gtecsfield=Other.Field”`
gtefieldField Greater Than or Equal To Another Field 必须大于等于 Field 的值
gtfieldField Greater Than Another Field 必须大于 Field 的值
ltcsfieldLess Than Another Relative Field 必须小于 struct Other 中 Field 的值 例: binding:“ltcsfield=Other.Field”`
ltecsfieldLess Than or Equal To Another Relative Field 必须小于等于 struct Other 中 Field 的值 例: binding:“ltecsfield=Other.Field”`
ltefieldLess Than or Equal To Another Field 必须小于等于 Field 的值
ltfieldLess Than Another Field 必须小于 Field 的值
necsfieldField Does Not Equal Another Field (relative) 必须不等于 struct Other 中 Field 的值 例: binding:“necsfield=Other.Field”`
nefieldField Does Not Equal Another Field 必须不等 Field

Network:

TagDescription
cidrClassless Inter-Domain Routing CIDR
cidrv4Classless Inter-Domain Routing CIDRv4
cidrv6Classless Inter-Domain Routing CIDRv6
datauriData URL
fqdnFull Qualified Domain Name (FQDN)
hostnameHostname RFC 952
hostname_portHostPort
hostname_rfc1123Hostname RFC 1123
ipInternet Protocol Address IP
ip4_addrInternet Protocol Address IPv4
ip6_addrInternet Protocol Address IPv6
ip_addrInternet Protocol Address IP
ipv4Internet Protocol Address IPv4
ipv6Internet Protocol Address IPv6
macMedia Access Control Address MAC
tcp4_addrTransmission Control Protocol Address TCPv4
tcp6_addrTransmission Control Protocol Address TCPv6
tcp_addrTransmission Control Protocol Address TCP
udp4_addrUser Datagram Protocol Address UDPv4
udp6_addrUser Datagram Protocol Address UDPv6
udp_addrUser Datagram Protocol Address UDP
unix_addrUnix domain socket end point Address
uriURI String
urlURL String 验证字符串值包含有效的网址
url_encodedURL Encoded
urn_rfc2141Urn RFC 2141 String

Strings:

TagDescription
alphaAlpha Only
alphanumAlphanumeric
alphanumunicodeAlphanumeric Unicode
alphaunicodeAlpha Unicode
asciiASCII
containsContains
containsanyContains Any
containsruneContains Rune
lowercaseLowercase
multibyteMulti-Byte Characters
numberNOT DOCUMENTED IN doc.go
numericNumeric
printasciiPrintable ASCII
startswithStarts With
uppercaseUppercase

Format:

TagDescription
base64Base64 String
base64urlBase64URL String
btc_addrBitcoin Address
btc_addr_bech32Bitcoin Bech32 Address (segwit)
datetimeDatetime
emailE-mail String 验证字符串是 email 格式
eth_addrEthereum Address
hexadecimalHexadecimal String
hexcolorHexcolor String
hslHSL String
hslaHSLA String
htmlHTML Tags
html_encodedHTML Encoded
isbnInternational Standard Book Number
isbn10International Standard Book Number 10
isbn13International Standard Book Number 13
jsonJSON
latitudeLatitude
longitudeLongitude
rgbRGB String
rgbaRGBA String
ssnSocial Security Number SSN
uuidUniversally Unique Identifier UUID
uuid3Universally Unique Identifier UUID v3
uuid3_rfc4122Universally Unique Identifier UUID v3 RFC4122
uuid4Universally Unique Identifier UUID v4
uuid4_rfc4122Universally Unique Identifier UUID v4 RFC4122
uuid5Universally Unique Identifier UUID v5
uuid5_rfc4122Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122Universally Unique Identifier UUID RFC4122

Comparisons:

Tag说明
eqEquals 数字等于 n,或者或者数组、切片、map 的 len 值为 n,即包含的项目数
gtGreater than 数字大于 n,或者或者数组、切片、map 的 len 值大于 n,即包含的项目数大于 n
gteGreater than or equal 数字大于或等于 n,或者或者数组、切片、map 的 len 值大于或等于 n,即包含的项目数大于或等于 n
ltLess Than 数字小于 n,或者或者数组、切片、map 的 len 值小于 n,即包含的项目数小于 n
lteLess Than or Equal 数字小于或等于 n,或者或者数组、切片、map 的 len 值小于或等于 n,即包含的项目数小于或等于 n
neNot Equal 数字不等于 n,或者或者数组、切片、map 的 len 值不等于为 n,即包含的项目数不为 n,其和 eq 相反

Other:

TagDescription
dirDirectory
e164NOT DOCUMENTED IN doc.go
endswithEnds With
excludesExcludes
excludesallExcludes All 不能包含特殊字符, 注意用十六进制表示 例: binding:“excludesall=0x2C”`
excludesruneExcludes Rune
fileFile path
isdefaultIs Default
lenLength 字符长度必须等于 n,或者数组、切片、map 的 len 值为 n,即包含的项目数
maxMaximum 字符串最大长度
minMinimum 字符串最小长度
oneofOne Of
requiredRequired 必须
required_withRequired With
required_with_allRequired With All
required_withoutRequired Without
required_without_allRequired Without All
uniqueUnique

后记

官方验证事例 看这里

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