Skip to content

Suggest: How to Use Custom Binder #438

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

Closed
iktakahiro opened this issue Mar 30, 2016 · 7 comments
Closed

Suggest: How to Use Custom Binder #438

iktakahiro opened this issue Mar 30, 2016 · 7 comments
Assignees

Comments

@iktakahiro
Copy link

I'd like to suggest that adding a practice to the document.

  • CustomBinder - Json Binding with validation
type ValidateBinder struct{}

func (ValidateBinder) Bind(i interface{}, c echo.Context) (err error) {
    rq := c.Request()
    ct := rq.Header().Get(echo.ContentType)
    err = echo.ErrUnsupportedMediaType
    if strings.HasPrefix(ct, echo.ApplicationJSON) {
        if err = json.NewDecoder(rq.Body()).Decode(i); err != nil {
            return
        }
        if tagName := c.Get("ValidateTagName"); tagName == nil {
            c.Set("ValidateTagName", "validate")
        }
        config := &validator.Config{TagName: c.Get("ValidateTagName").(string)}
        validate := validator.New(config)
        if err = validate.Struct(i); err != nil {
            return
        }
    }
    return
}
  • Set CustomBinder
e := echo.New()
e.SetBinder(&ValidateBinder{})
  • How to Use
type User struct {
    ID    int64     `json:"id" validate:"required"`
    Email string    `json:"email" validate:"required,email"`
}

func MyFunc() echo.HandlerFunc {
    return func(c echo.Context) (err error) {

            user := new(model.User)
            c.Set("ValidateTagName", "validate")

            if err = c.Bind(user); err != nil {
               return echo.NewHTTPError(fasthttp.StatusBadRequest, "Request parameters are invalid.")
            }
    }
}
@LuisUrrutia
Copy link

+1

@vishr vishr closed this as completed in 01334bc Dec 13, 2016
@vishr vishr self-assigned this Apr 26, 2017
@chrislewispac
Copy link

i get the following err with this

e.SetBinder undefined (type *echo.Echo has no field or method SetBinder)

@vishr
Copy link
Member

vishr commented May 5, 2017

@chrislewispac In Echo v3, the property is directly exposed. So you do e.Binder =

@shyandsy
Copy link

how to use customerBind in v4? any documents?

@Gaadek
Copy link

Gaadek commented Oct 9, 2020

Hello, In case of, the custom binder in Echo v4 can be implemented this way:

package main

import (
	"fmt"
	"net/http"

	"github.com/labstack/echo/v4"
)

type CustomBinder struct{}

func (cb *CustomBinder) Bind(i interface{}, c echo.Context) (err error) {
	// You may use default binder
	db := &echo.DefaultBinder{}
	if err = db.Bind(i, c); err != echo.ErrUnsupportedMediaType {
		return
	}

	// Then define your custom implementation
	println("And now for some logic")

	return
}

func handler(c echo.Context) error {
	req := new(Request)
	if err := c.Bind(req); err != nil {
		return err
	}
	return c.String(http.StatusOK, fmt.Sprint("all good, req = ", req))
}

func main() {
	e := echo.New()
	e.Binder := &CustomBinder{}
	e.POST("/", handler)
	e.Start(":3000")
}

@mrccnt
Copy link

mrccnt commented Nov 20, 2020

Besides that that it should be req := new(http.Request) and e.Binder = &CustomBinder{} this snippet does not work. The println("And now for some logic") never gets printed. The default binder is still used.

Any ideas whats wrong?

@mrccnt
Copy link

mrccnt commented Nov 20, 2020

Ok guess I got it. The err != echo.ErrUnsupportedMediaType comparison prevents execution. Here a full example using custom binder and custom validator more or less straight from the examples:

package main

import (
	"github.com/go-playground/validator/v10"
	"github.com/labstack/echo/v4"
	"net/http"
)

type CustomBinder struct {}

type CustomValidator struct {
	validator *validator.Validate
}

type User struct {
	Name  string `json:"name"  validate:"required"`
	Email string `json:"email" validate:"required,email"`
}

func main() {

	e := echo.New()
	e.Binder = new(CustomBinder)
	e.Validator = &CustomValidator{validator: validator.New()}

	e.POST("/users", func(c echo.Context) error {
		u := new(User)
		if err := c.Bind(u); err != nil {
		    return err
		}
		if err := c.Validate(u); err != nil {
		    return err
		}
		return c.JSON(http.StatusOK, u)
	})

	e.Logger.Fatal(e.Start(":1323"))

}

func (cb *CustomBinder) Bind(i interface{}, c echo.Context) error {
	db := new(echo.DefaultBinder)
	if err := db.Bind(i, c); err != nil {
	    return err
	}
	println("CustomBinder", "Bind")
	return nil
}

func (cv *CustomValidator) Validate(i interface{}) error {
	println("CustomValidator", "Validate")
	return cv.validator.Struct(i)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants