-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
103 lines (87 loc) · 2.59 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
// album represents data about a record album.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// albums slice to seed record album data.
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 main() {
router := gin.Default()
router.GET("/", func(context *gin.Context) {
context.IndentedJSON(http.StatusOK, "Hello")
})
router.GET("/albums", func(c *gin.Context) {
if c.Query("maxPrice") != "" {
getAlbumsMaxPrice(c)
} else {
getAlbums(c)
}
})
router.GET("/albums/:id", getAlbumByID)
router.POST("/albums", postAlbums)
err := router.Run(":8080")
if err != nil {
println("Unable to start router.")
return
}
}
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
c.IndentedJSON(http.StatusOK, albums)
}
// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
var newAlbum album
// Call BindJSON to bind the received JSON to newAlbum.
if err := c.BindJSON(&newAlbum); err != nil {
return
}
albums = append(albums, newAlbum)
c.IndentedJSON(http.StatusCreated, newAlbum)
}
// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
id := c.Param("id")
// Loop over the list of albums, looking for
// an album whose ID value matches the parameter.
for _, a := range albums {
if a.ID == id {
c.IndentedJSON(http.StatusOK, a)
return
}
}
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
// getAlbumsMaxPrice responds with the list of all albums with a price less than or equal to than the given param as JSON.
func getAlbumsMaxPrice(c *gin.Context) {
maxPrice, err := strconv.ParseFloat(c.Query("maxPrice"), 64)
if err != nil {
c.IndentedJSON(http.StatusBadRequest, gin.H{"message": "query must be a number"})
}
var matches []album
// Loop over the list of albums, looking for
// albums whose price value is less than the parameter.
for _, a := range albums {
if a.Price <= maxPrice {
matches = append(matches, a)
}
}
if len(matches) > 0 {
c.IndentedJSON(http.StatusOK, matches)
} else {
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "no matches found"})
}
}