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.
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.
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. ...