echo
echo copied to clipboard
Support to Default param and query param
With this PR, I would like to add support for setting a default value if c.Param or c.QueryParam is empty.
Adding new methods to Context interface is problematic due backwards compatibility semantic versioning provides.
There is a way to have default bind values already in library. See this example:
func main() {
e := echo.New()
e.GET("/products/:category", func(c echo.Context) error {
opts := SearchOpts{
Category: "cars", // defaults to 'cars'
Limit: 50, // defaults to 50
Language: "",
}
err := echo.PathParamsBinder(c).
String("category", &opts.Category).
BindError()
if err != nil {
return err
}
err = echo.QueryParamsBinder(c).
Int64("limit", &opts.Limit).
String("lang", &opts.Language).
BindError() // could use `BindErrors() []error` also
if err != nil {
return err
}
return c.String(http.StatusOK, "OK")
})
log.Fatal(e.Start(":8080"))
}
type SearchOpts struct {
Category string
Limit int64
Language string
}
Notes for myself:
- probably needs methods for FORM values also (we have
FormValue(name string) string) - Echo and Gin API is quite similar. In Gin same methods have prefix instead of suffix
DefaultalaDefaultParam(...). Consider using prefix also in Echo. I need arises it would be easier to convert handlers from one library to other.