Search⌘ K

Handler Component Creation for REST API

Explore how to build handler components for a REST API using Go. Learn to create functions to get, create, update, and delete items while registering routes and testing with curl and Newman tools.

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.

Go (1.18.2)
// 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.

Go (1.18.2)
// 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. ...