Sometimes (often) you want to validate user inputs. After looking at some validation library we decided to use ozzo-validation. Your structure needs to implement :
ValidateWithContext(ctx context.Context) error
or Validate() error
Example
packagemainimport ("net/http" validation "github.com/alexisvisco/ozzo-validation/v4""github.com/alexisvisco/ozzo-validation/v4/is""github.com/go-chi/chi""github.com/alexisvisco/kcd")funcmain() { r := chi.NewRouter() r.Get("/{name}", kcd.Handler(YourHttpHandler, http.StatusOK)) _ = http.ListenAndServe(":3000", r)}// CreateCustomerInput is an example of input for an http request.typeCreateCustomerInputstruct { Name string`path:"name"`}func (c *CreateCustomerInput) Validate() error {return validation.ValidateStruct(c, validation.Field(&c.Name, validation.Required, is.Alpha))}// YourHttpHandler is here using the ctx of the request.funcYourHttpHandler(c *CreateCustomerInput) (*CreateCustomerInput, error) {return c, nil}// Test it : curl localhost:3000/alexis
If you test this code with a curl localhost:3000/123 you will get an error because the name must be alphabetical as described in the Validate function.
You will get something like this:
{"error_description": "the request has one or multiple invalid fields","error": "invalid_argument","fields": {"name":"must contain English letters only" }}