2022-04-18 23:35:16 +02:00
|
|
|
package main
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"net/http"
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
type media struct {
|
|
|
|
ID string `json: "id"`
|
|
|
|
Url string `json: "url"`
|
|
|
|
Title string `json: "title"`
|
|
|
|
Author string `json: "author"`
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
var songs = []media{
|
|
|
|
{ID: "1", Url: "https://www.youtube.com/watch?v=DmeUuoxyt_E", Title: "Rockstars", Author: "Nickelback"},
|
|
|
|
{ID: "2", Url: "https://www.youtube.com/watch?v=u9Dg-g7t2l4", Title: "The Sound Of Silence", Author: "Disturbed"},
|
|
|
|
{ID: "3", Url: "https://www.youtube.com/watch?v=uxUATkpMQ8A", Title: "Gives You Hell", Author: "The All-American Rejects"},
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
func getMedia(c *gin.Context) {
|
|
|
|
c.IndentedJSON(http.StatusOK, songs)
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
func songByid(c *gin.Context) {
|
|
|
|
id := c.Param("id")
|
|
|
|
song, err := getMediaByid(id)
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
if err != nil {
|
|
|
|
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book not found."})
|
|
|
|
return
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
c.IndentedJSON(http.StatusOK, song)
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
func getMediaByid(id string) (*media, error) {
|
|
|
|
for i, song := range songs {
|
|
|
|
if song.ID == id {
|
|
|
|
return &songs[i], nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, errors.New("id not found")
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
func addMedia(c *gin.Context) {
|
|
|
|
var newSong media
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
if err := c.BindJSON(&newSong); err != nil {
|
|
|
|
return
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
songs = append(songs, newSong)
|
|
|
|
c.IndentedJSON(http.StatusCreated, newSong)
|
|
|
|
}
|
2022-04-11 23:49:18 +02:00
|
|
|
|
2022-04-18 23:35:16 +02:00
|
|
|
func main() {
|
|
|
|
router := gin.Default()
|
|
|
|
router.GET("/songs", getMedia)
|
|
|
|
router.GET("/songs/:id", songByid)
|
|
|
|
router.POST("/songs", addMedia)
|
|
|
|
router.Run("127.0.0.1:8000")
|
|
|
|
}
|