Git structure files
This commit is contained in:
65
test/main-songs.go
Normal file
65
test/main-songs.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type media struct {
|
||||
ID string `json: "id"`
|
||||
Url string `json: "url"`
|
||||
Title string `json: "title"`
|
||||
Author string `json: "author"`
|
||||
}
|
||||
|
||||
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"},
|
||||
}
|
||||
|
||||
func getMedia(c *gin.Context) {
|
||||
c.IndentedJSON(http.StatusOK, songs)
|
||||
}
|
||||
|
||||
func songByid(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
song, err := getMediaByid(id)
|
||||
|
||||
if err != nil {
|
||||
c.IndentedJSON(http.StatusNotFound, gin.H{"message": "Book not found."})
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, song)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
func addMedia(c *gin.Context) {
|
||||
var newSong media
|
||||
|
||||
if err := c.BindJSON(&newSong); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
songs = append(songs, newSong)
|
||||
c.IndentedJSON(http.StatusCreated, newSong)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
Reference in New Issue
Block a user