66 lines
1.8 KiB
Go
66 lines
1.8 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"arimelody.me/arimelody.me/global"
|
|
"arimelody.me/arimelody.me/music/model"
|
|
controller "arimelody.me/arimelody.me/music/controller"
|
|
)
|
|
|
|
func CreateMusicLink() http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
type linkJSON struct {
|
|
Release string
|
|
Name string
|
|
URL string
|
|
}
|
|
|
|
var data linkJSON
|
|
err := json.NewDecoder(r.Body).Decode(&data)
|
|
if err != nil {
|
|
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if data.Release == "" {
|
|
http.Error(w, "Release cannot be empty\n", http.StatusBadRequest)
|
|
return
|
|
}
|
|
if data.Name == "" {
|
|
http.Error(w, "Link name cannot be empty\n", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var release = global.GetRelease(data.Release)
|
|
if release == nil {
|
|
http.Error(w, fmt.Sprintf("Release %s does not exist\n", data.Release), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
var link = model.Link{
|
|
Name: data.Name,
|
|
URL: data.URL,
|
|
}
|
|
|
|
err = controller.CreateLinkDB(global.DB, release.ID, &link)
|
|
if err != nil {
|
|
fmt.Printf("Failed to create link: %s\n", err)
|
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
release.Links = append(release.Links, &link)
|
|
|
|
w.Header().Add("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusCreated)
|
|
err = json.NewEncoder(w).Encode(release.Links)
|
|
})
|
|
}
|