File tree 1 file changed +13
-2
lines changed
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
84
84
Example below uses https://github.com/go-playground/validator framework for validation:
85
85
86
86
``` 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
+
87
97
type (
88
98
User struct {
89
99
Name string ` json:"name" validate:"required"`
@@ -97,7 +107,8 @@ type (
97
107
98
108
func (cv *CustomValidator ) Validate (i interface {}) error {
99
109
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 ())
101
112
}
102
113
return nil
103
114
}
@@ -111,7 +122,7 @@ func main() {
111
122
return echo.NewHTTPError (http.StatusBadRequest , err.Error ())
112
123
}
113
124
if err = c.Validate (u); err != nil {
114
- return echo. NewHTTPError (http. StatusBadRequest , err. Error ())
125
+ return err
115
126
}
116
127
return c.JSON (http.StatusOK , u)
117
128
})
You can’t perform that action at this time.
0 commit comments