-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
78 lines (60 loc) · 1.74 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type ID string
type album struct {
ID ID `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
func getAlbums(c *gin.Context) {
// Calling Context.IntendedJSON to serialize the struct into JSON and add it to the response.
c.IndentedJSON(http.StatusOK, albums)
}
func postAlbums(c *gin.Context) {
var newAlbum album
// Get the memory address of the newAlbum variable to bind the json get from the gin context
if err := c.BindJSON(&newAlbum); err != nil {
return
}
// Add the new album to the slice.
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
func getSpecificAlbum(c *gin.Context) {
id := ID(c.Param("id"))
for _, album := range albums {
if album.ID == id {
c.IndentedJSON(http.StatusOK, album)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
func deleteSpecificAlbum(c *gin.Context) {
id := ID(c.Param("id"))
for i, album := range albums {
if album.ID == id {
albums = append(albums[:i], albums[i+1:]...)
c.IndentedJSON(http.StatusOK, albums)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.POST("/albums", postAlbums)
router.GET("/albums/:id", getSpecificAlbum)
router.DELETE("/albums/:id", deleteSpecificAlbum)
router.Run(":8080")
}