From e7db5ce5ac865b7966da12a6944058ec3e0d0014 Mon Sep 17 00:00:00 2001 From: qywok <59132829+belajarqywok@users.noreply.github.com> Date: Wed, 20 Oct 2021 16:39:14 +0700 Subject: [PATCH] Create main.go --- Task 2/AbhayRay_portfolio/main.go | 55 +++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Task 2/AbhayRay_portfolio/main.go diff --git a/Task 2/AbhayRay_portfolio/main.go b/Task 2/AbhayRay_portfolio/main.go new file mode 100644 index 00000000..201397c5 --- /dev/null +++ b/Task 2/AbhayRay_portfolio/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +type album struct { + ID string `json:"id"` + Title string `json:"title"` + Artist string `json:"artist"` +} + +var albums = []album{ + {ID: "1", Title: "asdasd", Artist: "asdasdasdas"}, + {ID: "2", Title: "asdasd", Artist: "asdasdasdas",}, + {ID: "3", Title: "asdasd", Artist: "asdasdasdaa",}, +} + +func main() { + router := gin.Default() + router.GET("/test", getAlbums) + router.GET("/test/:id", getAlbumByID) + router.POST("/post_test", postAlbums) + + router.Run("0.0.0.0:666") +} + +func getAlbums(c *gin.Context) { + c.IndentedJSON(http.StatusOK, albums) +} + +func postAlbums(c *gin.Context) { + var newAlbum album + + if err := c.BindJSON(&newAlbum); err != nil { + return + } + + albums = append(albums, newAlbum) + c.IndentedJSON(http.StatusCreated, newAlbum) +} + +func getAlbumByID(c *gin.Context) { + id := c.Param("id") + + for _, a := range albums { + if a.ID == id { + c.IndentedJSON(http.StatusOK, a) + return + } + } + c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"}) +}