added post method to add new albums, and new get method to get album by specific id
This commit is contained in:
parent
7bd27a591d
commit
f640ccc43d
1 changed files with 33 additions and 0 deletions
33
main.go
33
main.go
|
@ -6,6 +6,37 @@ import (
|
|||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Add the new album to the slice.
|
||||
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"})
|
||||
}
|
||||
|
||||
// album represents data about a record album.
|
||||
type album struct {
|
||||
ID string `json:"id"`
|
||||
|
@ -24,6 +55,8 @@ var albums = []album{
|
|||
func main() {
|
||||
router := gin.Default()
|
||||
router.GET("/albums", getAlbums)
|
||||
router.GET("/albums/:id", getAlbumByID)
|
||||
router.POST("/albums", postAlbums)
|
||||
|
||||
router.Run("localhost:8080")
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue