Skip to content
Myr

feat(binding): add support for custom validator / validation tags (#1068)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* feat(binding): Add support for custom validation tags * docs: Add example for custom validation tag * test(binding): Add test for registering custom validation

authored by Suhas Karanth · committed by Javier Provecho Fernandez · parent 030b1aa · Browse files · 5 files+175 added−13 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+175 added−13 removed

  • other:+175 added−13 removed

5 files+175 added−13 removed

modified:binding/binding.go+10 added-1 removed
2 unmodified lines
3// license that can be found in the LICENSE file.45package binding67import "net/http"7import (8 "net/http"910 validator "gopkg.in/go-playground/validator.v8"11)1213const (14 MIMEJSON = "application/json"15 MIMEHTML = "text/html"16 MIMEXML = "application/xml"
17 unmodified lines
34 // If the received type is a struct or pointer to a struct, the validation should be performed.35 // If the struct is not valid or the validation itself fails, a descriptive error should be returned.36 // Otherwise nil must be returned.37 ValidateStruct(interface{}) error3839 // 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) error43}4445var Validator StructValidator = &defaultValidator{}46
36 unmodified lines
modified:binding/default_validator.go+5 added
26 unmodified lines
27 }28 return nil29}3031func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error {32 v.lazyinit()33 return v.validate.RegisterValidation(key, fn)34}3536func (v *defaultValidator) lazyinit() {37 v.once.Do(func() {38 config := &validator.Config{TagName: "binding"}39 v.validate = validator.New(config)
11 unmodified lines
modified:binding/validate_test.go+42 added
4 unmodified lines
5package binding67import (8 "bytes"9 "reflect"10 "testing"11 "time"1213 validator "gopkg.in/go-playground/validator.v8"1415 "github.com/stretchr/testify/assert"16)1718type testInterface interface {
173 unmodified lines
192 assert.NoError(t, validate(str))193 assert.NoError(t, validate(&str))194 assert.Equal(t, str, "value")195}196197// structCustomValidation is a helper struct we use to check that198// custom validation can be registered on it.199// The `notone` binding directive is for custom validation and registered later.200type structCustomValidation struct {201 Integer int `binding:"notone"`202}203204// notOne is a custom validator meant to be used with `validator.v8` library.205// The method signature for `v9` is significantly different and this function206// would need to be changed for tests to pass after upgrade.207// See https://github.com/gin-gonic/gin/pull/1015.208func notOne(209 v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,210 field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,211) bool {212 if val, ok := field.Interface().(int); ok {213 return val != 1214 }215 return false216}217218func TestRegisterValidation(t *testing.T) {219 // This validates that the function `notOne` matches220 // the expected function signature by `defaultValidator`221 // and by extension the validator library.222 err := Validator.RegisterValidation("notone", notOne)223 // Check that we can register custom validation without error224 assert.Nil(t, err)225226 // Create an instance which will fail validation227 withOne := structCustomValidation{Integer: 1}228 errs := validate(withOne)229230 // Check that we got back non-nil errs231 assert.NotNil(t, errs)232 // Check that the error matches expactation233 assert.Error(t, errs, "", "", "notone")234}
added:examples/custom-validation/server.go+45 added
1package main23import (4 "net/http"5 "reflect"6 "time"78 "github.com/gin-gonic/gin"9 "github.com/gin-gonic/gin/binding"10 validator "gopkg.in/go-playground/validator.v8"11)1213type Booking struct {14 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`15 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`16}1718func bookableDate(19 v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,20 field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,21) bool {22 if date, ok := field.Interface().(time.Time); ok {23 today := time.Now()24 if today.Year() > date.Year() || today.YearDay() > date.YearDay() {25 return false26 }27 }28 return true29}3031func main() {32 route := gin.Default()33 binding.Validator.RegisterValidation("bookabledate", bookableDate)34 route.GET("/bookable", getBookable)35 route.Run(":8085")36}3738func getBookable(c *gin.Context) {39 var b Booking40 if err := c.ShouldBindWith(&b, binding.Query); err == nil {41 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})42 } else {43 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})44 }45}
modified:README.md+73 added-12 removed
38 unmodified lines
39```4041## Benchmarks4243Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) 43Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)4445[See all benchmarks](/BENCHMARKS.md)4647Benchmark name | (1) | (2) | (3) | (4)
25 unmodified lines
73BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 | 537474BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 2184875BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 6097677(1): Total Repetitions achieved in constant time, higher means more confident result 78(2): Single Repetition Duration (ns/op), lower is better 79(3): Heap Memory (B/op), lower is better 80(4): Average Allocations per Repetition (allocs/op), lower is better 77(1): Total Repetitions achieved in constant time, higher means more confident result78(2): Single Repetition Duration (ns/op), lower is better79(3): Heap Memory (B/op), lower is better80(4): Average Allocations per Repetition (allocs/op), lower is better8182## Gin v1. stable8384- [x] Zero allocation router.
195 unmodified lines
280 router.POST("/upload", func(c *gin.Context) {281 // single file282 file, _ := c.FormFile("file")283 log.Println(file.Filename)284 284285 // Upload the file to specific dst.286 // c.SaveUploadedFile(file, dst) 287 286 // c.SaveUploadedFile(file, dst)287288 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))289 })290 router.Run(":8080")291}
20 unmodified lines
312 files := form.File["upload[]"]313314 for _, file := range files {315 log.Println(file.Filename)316 316317 // Upload the file to specific dst.318 // c.SaveUploadedFile(file, dst) 318 // c.SaveUploadedFile(file, dst)319 }320 c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))321 })322 router.Run(":8080")
163 unmodified lines
486 router.Run(":8080")487}488```489490### Custom Validators491492It is also possible to register custom validators. See the [example code](examples/custom-validation/server.go).493494[embedmd]:# (examples/custom-validation/server.go go)495```go496package main497498import (499 "net/http"500 "reflect"501 "time"502503 "github.com/gin-gonic/gin"504 "github.com/gin-gonic/gin/binding"505 validator "gopkg.in/go-playground/validator.v8"506)507508type Booking struct {509 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`510 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`511}512513func bookableDate(514 v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,515 field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,516) bool {517 if date, ok := field.Interface().(time.Time); ok {518 today := time.Now()519 if today.Year() > date.Year() || today.YearDay() > date.YearDay() {520 return false521 }522 }523 return true524}525526func main() {527 route := gin.Default()528 binding.Validator.RegisterValidation("bookabledate", bookableDate)529 route.GET("/bookable", getBookable)530 route.Run(":8085")531}532533func getBookable(c *gin.Context) {534 var b Booking535 if err := c.ShouldBindWith(&b, binding.Query); err == nil {536 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})537 } else {538 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})539 }540}541```542543```console544$ curl "localhost:8085/bookable?check_in=2017-08-16&check_out=2017-08-17"545{"message":"Booking dates are valid!"}546547$ curl "localhost:8085/bookable?check_in=2017-08-15&check_out=2017-08-16"548{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}549```550551### Only Bind Query String552553`BindQuery` 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).554
216 unmodified lines
771772 // Listen and serve on 0.0.0.0:8080773 r.Run(":8080")774}714``` 775```776777### Serving static files778779```go
102 unmodified lines
882```go883 r := gin.Default()884 r.Delims("{[{", "}]}")885 r.LoadHTMLGlob("/path/to/templates"))825``` 886```887888#### Custom Template Funcs889890See the detail [example code](examples/template).
342 unmodified lines