echo icon indicating copy to clipboard operation
echo copied to clipboard

Support to Default param and query param

Open lucasmdomingues opened this issue 4 years ago • 2 comments

With this PR, I would like to add support for setting a default value if c.Param or c.QueryParam is empty.

lucasmdomingues avatar Nov 04 '21 23:11 lucasmdomingues

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
}

aldas avatar Nov 05 '21 04:11 aldas

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 Default ala DefaultParam(...). Consider using prefix also in Echo. I need arises it would be easier to convert handlers from one library to other.

aldas avatar Nov 14 '21 15:11 aldas