Read

After creating, of course, the next step would be to retrieve the created hotels. There are two APIs here:

  • GET /v1/hotels: Returns all the hotels that we have
  • GET /v1/hotels/<id>: Returns data about a specific hotel

The getHotel() method retrieves information about a specific hotel, whose ID is given in the path parameter defined. The code is pretty straightforward:

func getHotel(c *gin.Context) { 
   // get ID from path param 
   hotelId:= c.Param("id") 
 
   // get hotel object from repository 
   hotel, found:= repository[hotelId] 
   fmt.Println(hotel, found, hotelId) 
   if !found { 
         c.JSON(http.StatusNotFound, gin.H{"status": "hotel with id not found"}) 
   } else { 
         c.JSON(http.StatusOK, gin.H{"result": hotel}) 
   } 
 
} 

The Param() method of the Gin request Context object gives the path parameter named as :id. So for example, if the URL is /v1/hotels/abc, then the value of hotelId will be abc, since the getHotel() handler is defined for the /v1/hotels/:id path, where ID is the path parameter.

The rest of the code is pretty self-explanatory. If a hotel with the ID is not found then HTTP status code 404 (http.StatusNotFound) is returned. Otherwise, the Hotel object is serialized to JSON and sent to the client.

The API call looks like this:

curl 127.0.0.1:8080/v1/hotels/xyz 

And the response is as follows:

{   
   "result":{   
      "xyz":{   
         "id":"xyz", 
         "display_name":"HotelXyz", 
         "star_rating":4, 
         "no_rooms":150, 
         "links":[   
            {   
               "href":"/v1/hotels/book", 
               "rel":"book", 
               "type":"POST" 
            } 
         ] 
      } 
   } 
} 
Note the HATEOAS links that had been populated in the create handler.

Now, let's look at the getAllHotels() method. It just dumps the repository into a JSON map. The code for it is as follows:

func getAllHotels(c *gin.Context) { 
   c.JSON(http.StatusOK, gin.H{"result": repository}) 
} 

One can call this API as follows:

curl 127.0.0.1:8080/v1/hotels 

This will return a JSON map of all hotels:

{   
   "result":{   
      "xyz":{   
         "id":"xyz", 
         "display_name":"HotelXyz", 
         "star_rating":4, 
         "no_rooms":150, 
         "links":[   
            {   
               "href":"/v1/hotels/book", 
               "rel":"book", 
               "type":"POST" 
            } 
         ] 
      } 
   } 
} 
..................Content has been hidden....................

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