Hero Image
Go articles

学会 gin 参数校验之 validator 库,看这一篇就足够了 字符串约束 excludesall:不包含参数中任意的 UNICODE 字符,例如 excludesall=ab excludesrune:不包含参数表示的 rune 字符,excludesrune=asong startswith:以参数子串为前缀,例如 startswith=hi endswith:以参数子串为后缀,例如 endswith=bye。 contains=:包含参数子串,例如 contains=email containsany:包含参数中任意的 UNICODE 字符,例如 containsany=ab containsrune:包含参数表示的 rune 字符,例如`containsrune=asong excludes:不包含参数子串,例如 excludes=email 范围约束 范围约束的字段类型分为三种: 对于数值,我们则可以约束其值 对于切片、数组和 map,我们则可以约束其长度 对于字符串,我们则可以约束其长度 常用 tag 介绍: ne:不等于参数值,例如 ne=5 gt:大于参数值,例如 gt=5 gte:大于等于参数值,例如 gte=50 lt:小于参数值,例如 lt=50 lte:小于等于参数值,例如 lte=50 oneof:只能是列举出的值其中一个,这些值必须是数值或字符串,以空格分隔,如果字符串中有空格,将字符串用单引号包围,例如 oneof=male female。 eq:等于参数值,注意与 len 不同。对于字符串,eq 约束字符串本身的值,而 len 约束字符串长度。例如 eq=10 len:等于参数值,例如 len=10 max:小于等于参数值,例如 max=10 min:大于等于参数值,例如 min=10 Fields 约束 eqfield:定义字段间的相等约束,用于约束同一结构体中的字段。例如:eqfield=Password eqcsfield:约束统一结构体中字段等于另一个字段(相对),确认密码时可以使用,例如:eqfiel=ConfirmPassword nefield:用来约束两个字段是否相同,确认两种颜色是否一致时可以使用,例如:nefield=Color1 necsfield:约束两个字段是否相同(相对) 常用约束 unique:指定唯一性约束,不同类型处理不同:

Hero Image
Gin 框架绑定 JSON 参数使用 jsoniter

Gin 框架绑定 JSON 参数使用 jsoniter simple go build -tags=jsoniter ./... custom implement BindingBody interface // github.com/gin-gonic/gin@v1.6.3/binding/binding.go:36 // Binding describes the interface which needs to be implemented for binding the // data present in the request such as JSON request body, query parameters or // the form POST. type Binding interface { Name() string Bind(*http.Request, interface{}) error } // BindingBody adds BindBody method to Binding. BindBody is similar with Bind, // but it reads the body from supplied bytes instead of req.Body. type BindingBody interface { Binding BindBody([]byte, interface{}) error } package custom import ( "bytes" "fmt" "io" "net/http" jsoniter "github.com/json-iterator/go" "github.com/gin-gonic/gin/binding" ) // BindingJSON 替换Gin默认的binding,支持更丰富JSON功能 var BindingJSON = jsonBinding{} // 可以自定义jsoniter配置或者添加插件 var json = jsoniter.ConfigCompatibleWithStandardLibrary type jsonBinding struct{} func (jsonBinding) Name() string { return "json" } func (jsonBinding) Bind(req *http.Request, obj interface{}) error { if req == nil || req.Body == nil { return fmt.Errorf("invalid request") } return decodeJSON(req.Body, obj) } func (jsonBinding) BindBody(body []byte, obj interface{}) error { return decodeJSON(bytes.NewReader(body), obj) } func decodeJSON(r io.Reader, obj interface{}) error { decoder := json.NewDecoder(r) if binding.EnableDecoderUseNumber { decoder.UseNumber() } if binding.EnableDecoderDisallowUnknownFields { decoder.DisallowUnknownFields() } if err := decoder.Decode(obj); err != nil { return err } return validate(obj) } func validate(obj interface{}) error { if binding.Validator == nil { return nil } return binding.Validator.ValidateStruct(obj) } // binding.JSON 替换成自定义的 ctx.ShouldBindWith(ms, binding.JSON) ctx.ShouldBindBodyWith(ms, binding.JSON)