File tree Expand file tree Collapse file tree 1 file changed +13
-2
lines changed Expand file tree Collapse file tree 1 file changed +13
-2
lines changed Original file line number Diff line number Diff line change @@ -84,6 +84,16 @@ a custom validator using `Echo#Validator` and leverage third-party [libraries](h
8484Example below uses https://github.com/go-playground/validator framework for validation:
8585
8686``` go
87+ package main
88+
89+ import (
90+ " net/http"
91+
92+ " github.com/go-playground/validator"
93+ " github.com/labstack/echo/v4"
94+ " github.com/labstack/echo/v4/middleware"
95+ )
96+
8797type (
8898 User struct {
8999 Name string ` json:"name" validate:"required"`
@@ -97,7 +107,8 @@ type (
97107
98108func (cv *CustomValidator ) Validate (i interface {}) error {
99109 if err := cv.validator .Struct (i); err != nil {
100- return echo.NewHTTPError (http.StatusInternalServerError , err.Error ())
110+ // Optionally, you could return the error to give each route more control over the status code
111+ return echo.NewHTTPError (http.StatusBadRequest , err.Error ())
101112 }
102113 return nil
103114}
@@ -111,7 +122,7 @@ func main() {
111122 return echo.NewHTTPError (http.StatusBadRequest , err.Error ())
112123 }
113124 if err = c.Validate (u); err != nil {
114- return echo. NewHTTPError (http. StatusBadRequest , err. Error ())
125+ return err
115126 }
116127 return c.JSON (http.StatusOK , u)
117128 })
You can’t perform that action at this time.
0 commit comments