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
Provenance
- Commit
26c3f42- Tree
e55a9b9- Author
Suhas Karanth <sudo-suhas@users.noreply.github.com>- Committer
Javier Provecho Fernandez <javiertitan@gmail.com>- Parent
030b1aa
5 files changed+175 added−13 removed
modified:binding/binding.go+10 added-1 removed
2 unmodified lines3 // license that can be found in the LICENSE file.4 5 package binding6 7-import "net/http"7+import (8+ "net/http"9 10+ validator "gopkg.in/go-playground/validator.v8"11+)12+13 const (14 MIMEJSON = "application/json"15 MIMEHTML = "text/html"16 MIMEXML = "application/xml"17 unmodified lines34 // 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{}) error38+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) error43 }44 45 var Validator StructValidator = &defaultValidator{}46 36 unmodified linesmodified:binding/default_validator.go+5 added
26 unmodified lines27 }28 return nil29 }30 31+func (v *defaultValidator) RegisterValidation(key string, fn validator.Func) error {32+ v.lazyinit()33+ return v.validate.RegisterValidation(key, fn)34+}35+36 func (v *defaultValidator) lazyinit() {37 v.once.Do(func() {38 config := &validator.Config{TagName: "binding"}39 v.validate = validator.New(config)11 unmodified linesmodified:binding/validate_test.go+42 added
4 unmodified lines5 package binding6 7 import (8 "bytes"9+ "reflect"10 "testing"11 "time"12 13+ validator "gopkg.in/go-playground/validator.v8"14+15 "github.com/stretchr/testify/assert"16 )17 18 type testInterface interface {173 unmodified lines192 assert.NoError(t, validate(str))193 assert.NoError(t, validate(&str))194 assert.Equal(t, str, "value")195 }196+197+// 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.200+type structCustomValidation struct {201+ Integer int `binding:"notone"`202+}203+204+// 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.208+func 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+}217+218+func 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)225+226+ // Create an instance which will fail validation227+ withOne := structCustomValidation{Integer: 1}228+ errs := validate(withOne)229+230+ // 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
1+package main2+3+import (4+ "net/http"5+ "reflect"6+ "time"7+8+ "github.com/gin-gonic/gin"9+ "github.com/gin-gonic/gin/binding"10+ validator "gopkg.in/go-playground/validator.v8"11+)12+13+type 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+}17+18+func 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+}30+31+func main() {32+ route := gin.Default()33+ binding.Validator.RegisterValidation("bookabledate", bookableDate)34+ route.GET("/bookable", getBookable)35+ route.Run(":8085")36+}37+38+func 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 lines39 ```40 41 ## Benchmarks42 43-Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter) 43+Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)44 45 [See all benchmarks](/BENCHMARKS.md)46 47 Benchmark name | (1) | (2) | (3) | (4)25 unmodified lines73 BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 | 537474 BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 2184875 BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 60976 77-(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 better81 82 ## Gin v1. stable83 84 - [x] Zero allocation router.195 unmodified lines280 router.POST("/upload", func(c *gin.Context) {281 // single file282 file, _ := c.FormFile("file")283 log.Println(file.Filename)284- 284+285 // Upload the file to specific dst.286- // c.SaveUploadedFile(file, dst) 287- 286+ // c.SaveUploadedFile(file, dst)287+288 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))289 })290 router.Run(":8080")291 }20 unmodified lines312 files := form.File["upload[]"]313 314 for _, file := range files {315 log.Println(file.Filename)316- 316+317 // 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 lines486 router.Run(":8080")487 }488 ```489 490+### Custom Validators491+492+It is also possible to register custom validators. See the [example code](examples/custom-validation/server.go).493+494+[embedmd]:# (examples/custom-validation/server.go go)495+```go496+package main497+498+import (499+ "net/http"500+ "reflect"501+ "time"502+503+ "github.com/gin-gonic/gin"504+ "github.com/gin-gonic/gin/binding"505+ validator "gopkg.in/go-playground/validator.v8"506+)507+508+type 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+}512+513+func 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+}525+526+func main() {527+ route := gin.Default()528+ binding.Validator.RegisterValidation("bookabledate", bookableDate)529+ route.GET("/bookable", getBookable)530+ route.Run(":8085")531+}532+533+func 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+```542+543+```console544+$ curl "localhost:8085/bookable?check_in=2017-08-16&check_out=2017-08-17"545+{"message":"Booking dates are valid!"}546+547+$ 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+```550+551 ### Only Bind Query String552 553 `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 lines771 772 // Listen and serve on 0.0.0.0:8080773 r.Run(":8080")774 }714-``` 775+```776 777 ### Serving static files778 779 ```go102 unmodified lines882 ```go883 r := gin.Default()884 r.Delims("{[{", "}]}")885 r.LoadHTMLGlob("/path/to/templates"))825-``` 886+```887 888 #### Custom Template Funcs889 890 See the detail [example code](examples/template).342 unmodified lines