Post Handlers
This go boilerplate uses Echo. If you're ever in doubt, you can refer to Echo's documentation for more details on what's possible with routers.
A handler is any function with the func (c echo.Context) error
signature. All handlers should be stored under pkg/api/handlers
and categorized in directories following their entity name in plural form. For readability and maintainability, we encourage maintaining a single handler in a single file as we all know that Go files can quickly grow.
Handlers should also be nested, which means a Cats handlers directory can contain a sub directory, such as cats/tags
, that helps avoid long file names and improve readability.
How handlers look will largely depend on your project's business logic and requirements. For reference, here's a quick sample to give an idea on how you should construct your handler.
Create a cat handler
func Post(c echo.Context) error {
f := &models.CatForm{}
if err := c.Bind(f); err != nil {
return helpers.Error(c, constants.ERROR_BINDING_BODY, err)
}
if err := helpers.Validate(f); err != nil {
return c.JSON(http.StatusBadRequest, handlers.ValidationErrors(err))
}
m := f.MapToModel()
if err := m.Save(); err != nil {
return helpers.Error(c, err, nil)
}
return c.JSON(http.StatusOK, handlers.Success(m.MapToForm()))
}