Getting a full list of available products

First, let's create a method called GetProducts that takes the *gin.Context type as an argument:

func (h *Handler) GetProducts(c *gin.Context) {
}

Next, we need to ensure that our database interface is initialized and not nil, then we use the database layer interface in order to obtain the list of products:

func (h *Handler) GetProducts(c *gin.Context) {
if h.db == nil {
return
}
products, err := h.db.GetAllProducts()
}

Now, what happens if the call returns an error? We need to return a JSON document to the client with the error. The response to the client also needs to include an HTTP status code that indicates that the request failed. An HTTP status code is a way to report that an error happened in HTTP communication. This is where we start using the *gin.Context type, which includes a method called JSON() that we can use to return JSON documents:

func (h *Handler) GetProducts(c *gin.Context) {
if h.db == nil {
return
}
products, err := h.db.GetAllProducts()
if err != nil {
/*
First argument is the http status code, whereas the second argument is the body of the request
*/
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
}

Finally, if there is no error, then we return the list of products we retrieved from the database. Since we defined JSON struct tags in our data models, our data models will get converted to the JSON document formats that we defined:

func (h *Handler) GetProducts(c *gin.Context) {
if h.db == nil {
return
}
products, err := h.db.GetAllProducts()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, products)
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.214.155