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
Can I use this with Echo? #123
Comments
Yes you can. Code Examplepackage main
import (
"fmt"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"github.com/thedevsaddam/govalidator"
)
type Params struct {
Name string `query:"name" json:"name" form:"name"`
}
func main() {
e := echo.New()
e.GET("/", func(c echo.Context) error {
var u Params
if err := c.Bind(&u); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "failed to bind params")
}
opts := govalidator.Options{
Data: &u,
Rules: govalidator.MapData{
"name": []string{"required", "between:2,10"},
},
Messages: govalidator.MapData{
"name": []string{"required:Name cant be empty", "between:name needs to be between 2 and 10 characters"},
},
RequiredDefault: true,
}
v := govalidator.New(opts)
e := v.ValidateStruct()
if len(e) > 0 {
for k, v := range e {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Sprintf("%s: %s", k, strings.Join(v, ", ")))
}
return echo.NewHTTPError(http.StatusBadRequest, "unknown error during validation")
}
return c.String(http.StatusOK, fmt.Sprintf("Hi %s", u.Name))
})
e.Logger.Fatal(e.Start(":1323"))
} Result ExamplesGET http://127.0.0.1:1323/
{"message":"name: Name cant be empty, name needs to be between 2 and 10 characters"}
GET http://127.0.0.1:1323/?name=A
{"message":"name: name needs to be between 2 and 10 characters"}
GET http://127.0.0.1:1323/?name=ABC
Hi ABC Full Example https://github.com/Kirari04/echo-govalidator-example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can I use this with Echo?
The text was updated successfully, but these errors were encountered: