Skip to content
Myr

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

authored by Suhas Karanth · committed by Bo-Yi Wu · parent 65a65c2 · Browse files · 8 files+161 added−15 removed
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

8 files+161 added−15 removed

modified:binding/binding.go+17 added-6 removed
4 unmodified lines
5package binding67import (8 "net/http"910 "gopkg.in/go-playground/validator.v8"9)1011const (12 MIMEJSON = "application/json"
7 unmodified lines
20 MIMEMSGPACK = "application/x-msgpack"21 MIMEMSGPACK2 = "application/msgpack"22)2324// 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.27type Binding interface {28 Name() string29 Bind(*http.Request, interface{}) error30}3132// 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.36type 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{}) error4339 // 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}4849// 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.52var Validator StructValidator = &defaultValidator{}5354// These implement the Binding interface and can be used to bind the data55// present in the request to struct instances.56var (57 JSON = jsonBinding{}58 XML = xmlBinding{}59 Form = formBinding{}
3 unmodified lines
63 ProtoBuf = protobufBinding{}64 MsgPack = msgpackBinding{}65)6667// Default returns the appropriate Binding instance based on the HTTP method68// and the content type.69func Default(method, contentType string) Binding {70 if method == "GET" {71 return Form72 }
21 unmodified lines
modified:binding/default_validator.go+6 added-2 removed
26 unmodified lines
27 }28 return nil29}3031func (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.v835func (v *defaultValidator) Engine() interface{} {36 v.lazyinit()33 return v.validate.RegisterValidation(key, fn)37 return v.validate38}3940func (v *defaultValidator) lazyinit() {41 v.once.Do(func() {
13 unmodified lines
modified:binding/json.go+3 added
8 unmodified lines
910 "github.com/gin-gonic/gin/json"11)1213// 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.16var EnableDecoderUseNumber = false1718type jsonBinding struct{}19
14 unmodified lines
modified:binding/validate_test.go+6 added-3 removed
212 unmodified lines
213 }214 return false215}216217func TestRegisterValidation(t *testing.T) {217func 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)223221 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)227228 // Create an instance which will fail validation
1 unmodified line
230 errs := validate(withOne)231232 // 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 lines
29}3031func main() {32 route := gin.Default()3334 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {33 binding.Validator.RegisterValidation("bookabledate", bookableDate)35 v.RegisterValidation("bookabledate", bookableDate)36 }3738 route.GET("/bookable", getBookable)39 route.Run(":8085")40}41
8 unmodified lines
added:examples/struct-lvl-validations/README.md+50 added
added:examples/struct-lvl-validations/server.go+64 added
1package main23import (4 "net/http"5 "reflect"67 "github.com/gin-gonic/gin"8 "github.com/gin-gonic/gin/binding"9 validator "gopkg.in/go-playground/validator.v8"10)1112// User contains user information.13type User struct {14 FirstName string `json:"fname"`15 LastName string `json:"lname"`16 Email string `binding:"required,email"`17}1819// 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.28func UserStructLevelValidation(v *validator.Validate, structLevel *validator.StructLevel) {29 user := structLevel.CurrentStruct.Interface().(User)3031 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 }3940 // plus can to more, even with different tag than "fnameorlname"41}4243func main() {44 route := gin.Default()4546 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {47 v.RegisterStructValidation(UserStructLevelValidation, User{})48 }4950 route.POST("/user", validateUser)51 route.Run(":8085")52}5354func 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 lines
563}564565func main() {566 route := gin.Default()567568 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {567 binding.Validator.RegisterValidation("bookabledate", bookableDate)569 v.RegisterValidation("bookabledate", bookableDate)570 }571572 route.GET("/bookable", getBookable)573 route.Run(":8085")574}575
7 unmodified lines
583}584```585586```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!"}589586$ 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```593594[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registed this way.595See the [struct-lvl-validation example](examples/struct-lvl-validations) to learn more.596597### Only Bind Query String598599`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