Handler Component Creation for REST API
Learn how to create a handler component in a REST API with local storage.
Create the handler component
The service component is already created. The next step is to create a handler to use the service component. We create a directory called handlers
and then create a new file called handlers.go
to store the handler component.
Get all items
Inside the handlers.go
file, we create a function to get all items from the storage.
// GetAllItems returns all items from the storagefunc GetAllItems(c *fiber.Ctx) error {// get all itemsvar items []models.Item = services.GetAllItems()// return the responsereturn c.JSON(models.Response[[]models.Item]{Success: true,Message: "All items data",Data: items,})}
In the code above, all item data is retrieved from the GetAllItems()
method from the service component. Then the result from this method is returned.
Get item by ID
Inside the handlers.go
file, we create a function to get the item’s data by ID.
// GetItemByID returns item's data by IDfunc GetItemByID(c *fiber.Ctx) error {// get the id from the request parametervar itemID string = c.Params("id")// get the item by IDitem, err := services.GetItemByID(itemID)// if error is exists, return the error responseif err != nil {return c.Status(http.StatusNotFound).JSON(models.Response[any]{Success: false,Message: err.Error(),})}// return the itemreturn c.JSON(models.Response[models.Item]{Success: true,Message: "item found",Data: item,})}
In the code above, the item’s data is retrieved with the GetItemByID
method from the service component. If the item is found, the item’s data is returned. Otherwise, an error response is returned.