Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map validation, contextual validation, validator tags for custom map/slice types #2877

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 41 additions & 0 deletions README.md
Expand Up @@ -43,6 +43,7 @@ Gin is a web framework written in Go (Golang). It features a martini-like API wi
- [Controlling Log output coloring](#controlling-log-output-coloring)
- [Model binding and validation](#model-binding-and-validation)
- [Custom Validators](#custom-validators)
- [Custom Map and Slice Validator Tags](#custom-map-and-slice-validator-tags)
- [Only Bind Query String](#only-bind-query-string)
- [Bind Query String or Post Data](#bind-query-string-or-post-data)
- [Bind Uri](#bind-uri)
Expand Down Expand Up @@ -838,6 +839,46 @@ $ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"
[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.
See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.

### Custom Map and Slice Validator Tags

It is possible to register validator tags for custom map and slice types.

```go
package main

import (
"net/http"

"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)

type Person struct {
FirstName string `json:"firstName" binding:"required,lte=64"`
LastName string `json:"lastName" binding:"required,lte=64"`
}

type Managers map[string]Person

func main() {
route := gin.Default()

binding.RegisterValidatorTag("dive,keys,oneof=accounting finance operations,endkeys", Managers{})

route.POST("/managers", configureManagers)
route.Run(":8085")
}

func configureManagers(c *gin.Context) {
var m Managers
if err := c.ShouldBindJSON(&m); err == nil {
c.JSON(http.StatusOK, gin.H{"message": "Manager configuration is valid!"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
```

### Only Bind Query String

`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).
Expand Down
51 changes: 43 additions & 8 deletions binding/binding.go
Expand Up @@ -7,7 +7,10 @@

package binding

import "net/http"
import (
"context"
"net/http"
)

// Content-Type MIME of the most common data formats.
const (
Expand All @@ -32,29 +35,50 @@ type Binding interface {
Bind(*http.Request, interface{}) error
}

// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
// ContextBinding enables contextual validation by adding BindContext to Binding.
// Custom validators can take advantage of the information in the context.
type ContextBinding interface {
Binding
BindContext(context.Context, *http.Request, interface{}) error
}

// BindingBody adds BindBody method to Binding. BindBody is similar to Bind,
// but it reads the body from supplied bytes instead of req.Body.
type BindingBody interface {
Binding
BindBody([]byte, interface{}) error
}

// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it read the Params.
// ContextBindingBody enables contextual validation by adding BindBodyContext to BindingBody.
// Custom validators can take advantage of the information in the context.
type ContextBindingBody interface {
BindingBody
BindContext(context.Context, *http.Request, interface{}) error
BindBodyContext(context.Context, []byte, interface{}) error
}

// BindingUri is similar to Bind, but it read the Params.
type BindingUri interface {
Name() string
BindUri(map[string][]string, interface{}) error
}

// ContextBindingUri enables contextual validation by adding BindUriContext to BindingUri.
// Custom validators can take advantage of the information in the context.
type ContextBindingUri interface {
BindingUri
BindUriContext(context.Context, map[string][]string, interface{}) error
}

// StructValidator is the minimal interface which needs to be implemented in
// order for it to be used as the validator engine for ensuring the correctness
// of the request. Gin provides a default implementation for this using
// https://github.com/go-playground/validator/tree/v10.6.1.
type StructValidator interface {
// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
// If the received type is a slice|array, the validation should be performed travel on every element.
// If the received type is not a struct or slice|array, any validation should be skipped and nil must be returned.
// If the received type is a struct or pointer to a struct, the validation should be performed.
// If the received type is a slice/array/map, the validation should be performed on every element.
// If the received type is not a struct or slice/array/map, any validation should be skipped and nil must be returned.
// If the received type is a pointer to a struct/slice/array/map, the validation should be performed.
// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
// Otherwise nil must be returned.
ValidateStruct(interface{}) error
Expand All @@ -64,6 +88,14 @@ type StructValidator interface {
Engine() interface{}
}

// ContextStructValidator is an extension of StructValidator that requires implementing
// context-aware validation.
// Custom validators can take advantage of the information in the context.
type ContextStructValidator interface {
StructValidator
ValidateStructContext(context.Context, interface{}) error
}

// Validator is the default validator which implements the StructValidator
// interface. It uses https://github.com/go-playground/validator/tree/v10.6.1
// under the hood.
Expand Down Expand Up @@ -110,9 +142,12 @@ func Default(method, contentType string) Binding {
}
}

func validate(obj interface{}) error {
func validateContext(ctx context.Context, obj interface{}) error {
if Validator == nil {
return nil
}
if v, ok := Validator.(ContextStructValidator); ok {
return v.ValidateStructContext(ctx, obj)
}
return Validator.ValidateStruct(obj)
}
15 changes: 13 additions & 2 deletions binding/binding_msgpack_test.go
Expand Up @@ -9,6 +9,7 @@ package binding

import (
"bytes"
"context"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -35,7 +36,7 @@ func TestBindingMsgPack(t *testing.T) {
string(data), string(data[1:]))
}

func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body, badBody string) {
func testMsgPackBodyBinding(t *testing.T, b ContextBinding, name, path, badPath, body, badBody string) {
assert.Equal(t, name, b.Name())

obj := FooStruct{}
Expand All @@ -48,7 +49,17 @@ func testMsgPackBodyBinding(t *testing.T, b Binding, name, path, badPath, body,
obj = FooStruct{}
req = requestWithBody("POST", badPath, badBody)
req.Header.Add("Content-Type", MIMEMSGPACK)
err = MsgPack.Bind(req, &obj)
err = b.Bind(req, &obj)
assert.Error(t, err)

obj2 := ConditionalFooStruct{}
req = requestWithBody("POST", path, body)
req.Header.Add("Content-Type", MIMEMSGPACK)
err = b.BindContext(context.Background(), req, &obj2)
assert.NoError(t, err)
assert.Equal(t, "bar", obj2.Foo)

err = b.BindContext(context.WithValue(context.Background(), "condition", true), req, &obj2) // nolint
assert.Error(t, err)
}

Expand Down
52 changes: 44 additions & 8 deletions binding/binding_nomsgpack.go
Expand Up @@ -7,7 +7,10 @@

package binding

import "net/http"
import (
"context"
"net/http"
)

// Content-Type MIME of the most common data formats.
const (
Expand All @@ -30,28 +33,50 @@ type Binding interface {
Bind(*http.Request, interface{}) error
}

// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
// ContextBinding enables contextual validation by adding BindContext to Binding.
// Custom validators can take advantage of the information in the context.
type ContextBinding interface {
Binding
BindContext(context.Context, *http.Request, interface{}) error
}

// BindingBody adds BindBody method to Binding. BindBody is similar to Bind,
// but it reads the body from supplied bytes instead of req.Body.
type BindingBody interface {
Binding
BindBody([]byte, interface{}) error
}

// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,
// but it read the Params.
// ContextBindingBody enables contextual validation by adding BindBodyContext to BindingBody.
// Custom validators can take advantage of the information in the context.
type ContextBindingBody interface {
BindingBody
BindContext(context.Context, *http.Request, interface{}) error
BindBodyContext(context.Context, []byte, interface{}) error
}

// BindingUri is similar to Bind, but it read the Params.
type BindingUri interface {
Name() string
BindUri(map[string][]string, interface{}) error
}

// ContextBindingUri enables contextual validation by adding BindUriContext to BindingUri.
// Custom validators can take advantage of the information in the context.
type ContextBindingUri interface {
BindingUri
BindUriContext(context.Context, map[string][]string, interface{}) error
}

// StructValidator is the minimal interface which needs to be implemented in
// order for it to be used as the validator engine for ensuring the correctness
// of the request. Gin provides a default implementation for this using
// https://github.com/go-playground/validator/tree/v10.6.1.
type StructValidator interface {
// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
// If the received type is not a struct, any validation should be skipped and nil must be returned.
// If the received type is a struct or pointer to a struct, the validation should be performed.
// If the received type is a slice/array/map, the validation should be performed on every element.
// If the received type is not a struct or slice/array/map, any validation should be skipped and nil must be returned.
// If the received type is a pointer to a struct/slice/array/map, the validation should be performed.
// If the struct is not valid or the validation itself fails, a descriptive error should be returned.
// Otherwise nil must be returned.
ValidateStruct(interface{}) error
Expand All @@ -61,6 +86,14 @@ type StructValidator interface {
Engine() interface{}
}

// ContextStructValidator is an extension of StructValidator that requires implementing
// context-aware validation.
// Custom validators can take advantage of the information in the context.
type ContextStructValidator interface {
StructValidator
ValidateStructContext(context.Context, interface{}) error
}

// Validator is the default validator which implements the StructValidator
// interface. It uses https://github.com/go-playground/validator/tree/v10.6.1
// under the hood.
Expand All @@ -84,7 +117,7 @@ var (
// Default returns the appropriate Binding instance based on the HTTP method
// and the content type.
func Default(method, contentType string) Binding {
if method == "GET" {
if method == http.MethodGet {
return Form
}

Expand All @@ -104,9 +137,12 @@ func Default(method, contentType string) Binding {
}
}

func validate(obj interface{}) error {
func validateContext(ctx context.Context, obj interface{}) error {
if Validator == nil {
return nil
}
if v, ok := Validator.(ContextStructValidator); ok {
return v.ValidateStructContext(ctx, obj)
}
return Validator.ValidateStruct(obj)
}