...

/

Handler Component Creation for REST API

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 storage
func GetAllItems(c *fiber.Ctx) error {
// get all items
var items []models.Item = services.GetAllItems()
// return the response
return c.JSON(models.Response[[]models.Item]{
Success: true,
Message: "All items data",
Data: items,
})
}
Create a function to get all 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 ID
func GetItemByID(c *fiber.Ctx) error {
// get the id from the request parameter
var itemID string = c.Params("id")
// get the item by ID
item, err := services.GetItemByID(itemID)
// if error is exists, return the error response
if err != nil {
return c.Status(http.StatusNotFound).JSON(models.Response[any]{
Success: false,
Message: err.Error(),
})
}
// return the item
return c.JSON(models.Response[models.Item]{
Success: true,
Message: "item found",
Data: item,
})
}
Function to get all items by ID

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.

Create a new item

...