Uploader/main.go
AustrianToast 6171344b65
small change
modify so it matches the actual project
2024-02-23 23:57:41 +01:00

123 lines
2.8 KiB
Go

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// album represents data about a record album.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Filepath string `json:"filepath"`
}
// albums slice to seed record album data.
var albums = []album{
{ID: "1", Title: "Blue Train", Description: "John Coltrane", Filepath: "56.99"},
{ID: "2", Title: "Jeru", Description: "Gerry Mulligan", Filepath: "17.99"},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Description: "Sarah Vaughan", Filepath: "39.99"},
}
func remove(slice []album, s int) []album {
return append(slice[:s], slice[s+1:]...)
}
func main() {
router := gin.Default()
router.SetTrustedProxies(nil)
router.GET("/albums", getAlbums)
router.GET("/albums/:id", getAlbumByID)
router.POST("/albums", postAlbums)
router.DELETE("/albums", delAlbums)
router.DELETE("/albums/:id", delAlbumByID)
router.PATCH("/albums/:id", updateAlbum)
router.Run("localhost:8080")
}
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
c.JSON(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 {
c.Status(http.StatusBadRequest)
return
}
for _, a := range albums {
if a == newAlbum {
c.Status(http.StatusBadRequest)
return
}
}
// Add the new album to the slice.
albums = append(albums, newAlbum)
c.JSON(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 through the list of albums, looking for
// an album whose ID value matches the parameter.
for _, a := range albums {
if a.ID == id {
c.JSON(http.StatusOK, a)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
func delAlbums(c *gin.Context) {
albums = []album{}
c.JSON(http.StatusOK, albums)
}
func delAlbumByID(c *gin.Context) {
id := c.Param("id")
for s, a := range albums {
if a.ID == id {
albums = remove(albums, s)
c.JSON(http.StatusCreated, albums)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
func updateAlbum(c *gin.Context) {
id := c.Param("id")
var newAlbum album
if err := c.BindJSON(&newAlbum); err != nil {
return
}
for s, a := range albums {
if a.ID == id {
albums = remove(albums, s)
albums = append(albums, newAlbum)
c.JSON(http.StatusCreated, newAlbum)
return
}
}
c.JSON(http.StatusNotFound, gin.H{"message": "album not found"})
}