-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
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
Comments
+1 |
i get the following err with this e.SetBinder undefined (type *echo.Echo has no field or method SetBinder) |
@chrislewispac In Echo v3, the property is directly exposed. So you do |
how to use customerBind in v4? any documents? |
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")
} |
Besides that that it should be Any ideas whats wrong? |
Ok guess I got it. The 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)
} |
I'd like to suggest that adding a practice to the document.
The text was updated successfully, but these errors were encountered: