Put Handlers

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.

PUT/v1/cats/{:id}

Update cat with ID handler

func Get(c echo.Context) error {

	id := c.Param("id")

	if id == "" {
		return helpers.Error(c, constants.ERROR_ID_NOT_FOUND, nil)
	}

	m, err := models.CatModel().Find(id)

	if err != nil {
		return helpers.Error(c, err, nil)
	}

	return c.JSON(http.StatusOK, handlers.Success(m.MapToForm()))

}

Was this page helpful?

Consider supporting my work if you find it useful

Buy me a coffee