fix(binding): Expose validator engine used by the default Validator (#1277)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(binding): Expose validator engine used by the default Validator - Add func ValidatorEngine for returning the underlying validator engine used in the default StructValidator implementation. - Remove the function RegisterValidation from the StructValidator interface which made it immpossible to use a StructValidator implementation without the validator.v8 library. - Update and rename test for registering validation Test{RegisterValidation => ValidatorEngine}. - Update readme and example for registering custom validation. - Add example for registering struct level validation. - Add documentation for the following binding funcs/types: - Binding interface - StructValidator interface - Validator instance - Binding implementations - Default func * fix(binding): Move validator engine getter inside interface * docs: rm date cmd from custom validation demo
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+161 added−15 removed
- other:+161 added−15 removed
Provenance
- Commit
6d913fc- Tree
4c0acf0- Author
Suhas Karanth <sudo-suhas@users.noreply.github.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
65a65c2
8 files changed+161 added−15 removed
modified:binding/binding.go+17 added-6 removed
4 unmodified lines5 package binding6 7 import (8 "net/http"9-10- "gopkg.in/go-playground/validator.v8"9 )10 11 const (12 MIMEJSON = "application/json"7 unmodified lines20 MIMEMSGPACK = "application/x-msgpack"21 MIMEMSGPACK2 = "application/msgpack"22 )23 24+// Binding describes the interface which needs to be implemented for binding the25+// data present in the request such as JSON request body, query parameters or26+// the form POST.27 type Binding interface {28 Name() string29 Bind(*http.Request, interface{}) error30 }31 32+// StructValidator is the minimal interface which needs to be implemented in33+// order for it to be used as the validator engine for ensuring the correctness34+// of the reqest. Gin provides a default implementation for this using35+// https://github.com/go-playground/validator/tree/v8.18.2.36 type StructValidator interface {37 // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.38 // If the received type is not a struct, any validation should be skipped and nil must be returned.39 // If the received type is a struct or pointer to a struct, the validation should be performed.40 // If the struct is not valid or the validation itself fails, a descriptive error should be returned.41 // Otherwise nil must be returned.42 ValidateStruct(interface{}) error43 39- // RegisterValidation adds a validation Func to a Validate's map of validators denoted by the key40- // NOTE: if the key already exists, the previous validation function will be replaced.41- // NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation42- RegisterValidation(string, validator.Func) error44+ // Engine returns the underlying validator engine which powers the45+ // StructValidator implementation.46+ Engine() interface{}47 }48 49+// Validator is the default validator which implements the StructValidator50+// interface. It uses https://github.com/go-playground/validator/tree/v8.18.251+// under the hood.52 var Validator StructValidator = &defaultValidator{}53 54+// These implement the Binding interface and can be used to bind the data55+// present in the request to struct instances.56 var (57 JSON = jsonBinding{}58 XML = xmlBinding{}59 Form = formBinding{}3 unmodified lines63 ProtoBuf = protobufBinding{}64 MsgPack = msgpackBinding{}65 )66 67+// Default returns the appropriate Binding instance based on the HTTP method68+// and the content type.69 func Default(method, contentType string) Binding {70 if method == "GET" {71 return Form72 }21 unmodified linesmodified:binding/default_validator.go+6 added-2 removed
26 unmodified lines27 }28 return nil29 }30 31-func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error {31+// Engine returns the underlying validator engine which powers the default32+// Validator instance. This is useful if you want to register custom validations33+// or struct level validations. See validator GoDoc for more info -34+// https://godoc.org/gopkg.in/go-playground/validator.v835+func (v *defaultValidator) Engine() interface{} {36 v.lazyinit()33- return v.validate.RegisterValidation(key, fn)37+ return v.validate38 }39 40 func (v *defaultValidator) lazyinit() {41 v.once.Do(func() {13 unmodified linesmodified:binding/json.go+3 added
8 unmodified lines9 10 "github.com/gin-gonic/gin/json"11 )12 13+// EnableDecoderUseNumber is used to call the UseNumber method on the JSON14+// Decoder instance. UseNumber causes the Decoder to unmarshal a number into an15+// interface{} as a Number instead of as a float64.16 var EnableDecoderUseNumber = false17 18 type jsonBinding struct{}19 14 unmodified linesmodified:binding/validate_test.go+6 added-3 removed
212 unmodified lines213 }214 return false215 }216 217-func TestRegisterValidation(t *testing.T) {217+func TestValidatorEngine(t *testing.T) {218 // This validates that the function `notOne` matches219 // the expected function signature by `defaultValidator`220 // and by extension the validator library.221+ engine, ok := Validator.Engine().(*validator.Validate)222+ assert.True(t, ok)223+221- err := Validator.RegisterValidation("notone", notOne)224+ err := engine.RegisterValidation("notone", notOne)225 // Check that we can register custom validation without error226 assert.Nil(t, err)227 228 // Create an instance which will fail validation1 unmodified line230 errs := validate(withOne)231 232 // Check that we got back non-nil errs233 assert.NotNil(t, errs)231- // Check that the error matches expactation234+ // Check that the error matches expectation235 assert.Error(t, errs, "", "", "notone")236 }modified:examples/custom-validation/server.go+5 added-1 removed
28 unmodified lines29 }30 31 func main() {32 route := gin.Default()33+34+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {33- binding.Validator.RegisterValidation("bookabledate", bookableDate)35+ v.RegisterValidation("bookabledate", bookableDate)36+ }37+38 route.GET("/bookable", getBookable)39 route.Run(":8085")40 }41 8 unmodified linesadded:examples/struct-lvl-validations/README.md+50 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950## Struct level validations
Validations can also be registered at the `struct` level when field level validationsdon't make much sense. This can also be used to solve cross-field validation elegantly.Additionally, it can be combined with tag validations. Struct Level validations run afterthe structs tag validations.
### Example requests
```shell# Validation errors are generated for struct tags as well as at the struct level$ curl -s -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{}' | jq{ "error": "Key: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag\nKey: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag", "message": "User validation failed!"}
# Validation fails at the struct level because neither first name nor last name are present$ curl -s -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"email": "george@vandaley.com"}' | jq{ "error": "Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'fnameorlname' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'fnameorlname' tag", "message": "User validation failed!"}
# No validation errors when either first name or last name is present$ curl -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"fname": "George", "email": "george@vandaley.com"}'{"message":"User validation successful."}
$ curl -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"lname": "Contanza", "email": "george@vandaley.com"}'{"message":"User validation successful."}
$ curl -X POST http://localhost:8085/user \ -H 'content-type: application/json' \ -d '{"fname": "George", "lname": "Costanza", "email": "george@vandaley.com"}'{"message":"User validation successful."}```
### Useful links
- Validator docs - https://godoc.org/gopkg.in/go-playground/validator.v8#Validate.RegisterStructValidation- Struct level example - https://github.com/go-playground/validator/blob/v8.18.2/examples/struct-level/struct_level.go- Validator release notes - https://github.com/go-playground/validator/releases/tag/v8.7added:examples/struct-lvl-validations/server.go+64 added
1+package main2+3+import (4+ "net/http"5+ "reflect"6+7+ "github.com/gin-gonic/gin"8+ "github.com/gin-gonic/gin/binding"9+ validator "gopkg.in/go-playground/validator.v8"10+)11+12+// User contains user information.13+type User struct {14+ FirstName string `json:"fname"`15+ LastName string `json:"lname"`16+ Email string `binding:"required,email"`17+}18+19+// UserStructLevelValidation contains custom struct level validations that don't always20+// make sense at the field validation level. For example, this function validates that either21+// FirstName or LastName exist; could have done that with a custom field validation but then22+// would have had to add it to both fields duplicating the logic + overhead, this way it's23+// only validated once.24+//25+// NOTE: you may ask why wouldn't not just do this outside of validator. Doing this way26+// hooks right into validator and you can combine with validation tags and still have a27+// common error output format.28+func UserStructLevelValidation(v *validator.Validate, structLevel *validator.StructLevel) {29+ user := structLevel.CurrentStruct.Interface().(User)30+31+ if len(user.FirstName) == 0 && len(user.LastName) == 0 {32+ structLevel.ReportError(33+ reflect.ValueOf(user.FirstName), "FirstName", "fname", "fnameorlname",34+ )35+ structLevel.ReportError(36+ reflect.ValueOf(user.LastName), "LastName", "lname", "fnameorlname",37+ )38+ }39+40+ // plus can to more, even with different tag than "fnameorlname"41+}42+43+func main() {44+ route := gin.Default()45+46+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {47+ v.RegisterStructValidation(UserStructLevelValidation, User{})48+ }49+50+ route.POST("/user", validateUser)51+ route.Run(":8085")52+}53+54+func validateUser(c *gin.Context) {55+ var u User56+ if err := c.ShouldBindJSON(&u); err == nil {57+ c.JSON(http.StatusOK, gin.H{"message": "User validation successful."})58+ } else {59+ c.JSON(http.StatusBadRequest, gin.H{60+ "message": "User validation failed!",61+ "error": err.Error(),62+ })63+ }64+}modified:README.md+10 added-3 removed
562 unmodified lines563 }564 565 func main() {566 route := gin.Default()567+568+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {567- binding.Validator.RegisterValidation("bookabledate", bookableDate)569+ v.RegisterValidation("bookabledate", bookableDate)570+ }571+572 route.GET("/bookable", getBookable)573 route.Run(":8085")574 }575 7 unmodified lines583 }584 ```585 586 ```console583-$ curl "localhost:8085/bookable?check_in=2017-08-16&check_out=2017-08-17"587+$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"588 {"message":"Booking dates are valid!"}589 586-$ curl "localhost:8085/bookable?check_in=2017-08-15&check_out=2017-08-16"590+$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"591 {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}592 ```593 594+[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registed this way.595+See the [struct-lvl-validation example](examples/struct-lvl-validations) to learn more.596+597 ### Only Bind Query String598 599 `ShouldBindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017).600 806 unmodified lines