Facebook
From Juhena Begum, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 98
  1. // run main.go
  2. // address: http://localhost:8080/albums/2
  3. // created this using a web tutorial -- keeping the code so I can fiddle around with it
  4.  
  5. package main
  6.  
  7. import (
  8.         "net/http"
  9.  
  10.         "github.com/gin-gonic/gin"
  11. )
  12.  
  13. // album represents data about a record album.
  14. type album struct {
  15.         ID     string  `json:"id"`
  16.         Title  string  `json:"title"`
  17.         Artist string  `json:"artist"`
  18.         Price  float64 `json:"price"`
  19. }
  20.  
  21. // albums slice to seed record album data.
  22. var albums = []album{
  23.         {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
  24.         {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
  25.         {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
  26. }
  27.  
  28. func main() {
  29.         router := gin.Default()
  30.         router.GET("/albums", getAlbums)
  31.         router.GET("/albums/:id", getAlbumByID)
  32.         router.POST("/albums", postAlbums)
  33.  
  34.         router.Run("localhost:8080")
  35. }
  36.  
  37. // getAlbums responds with the list of all albums as JSON.
  38. func getAlbums(c *gin.Context) {
  39.         c.IndentedJSON(http.StatusOK, albums)
  40. }
  41.  
  42. // postAlbums adds an album from JSON received in the request body.
  43. func postAlbums(c *gin.Context) {
  44.         var newAlbum album
  45.  
  46.         // Call BindJSON to bind the received JSON to
  47.         // newAlbum.
  48.         if err := c.BindJSON(&newAlbum); err != nil {
  49.                 return
  50.         }
  51.  
  52.  
  53.         // Add the new album to the slice.
  54.         albums = append(albums, newAlbum)
  55.         c.IndentedJSON(http.StatusCreated, newAlbum)
  56. }
  57.  
  58. // getAlbumByID locates the album whose ID value matches the id
  59. // parameter sent by the client, then returns that album as a response.
  60. func getAlbumByID(c *gin.Context) {
  61.         id := c.Param("id")
  62.  
  63.         // Loop through the list of albums, looking for
  64.         // an album whose ID value matches the parameter.
  65.         for _, a := range albums {
  66.                 if a.ID == id {
  67.                         c.IndentedJSON(http.StatusOK, a)
  68.                         return
  69.                 }
  70.         }
  71.         c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
  72. }