package api import ( "encoding/json" "fmt" "net/http" "time" "arimelody.me/arimelody.me/admin" "arimelody.me/arimelody.me/global" "arimelody.me/arimelody.me/music/model" controller "arimelody.me/arimelody.me/music/controller" ) func ServeCatalog() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { releases := []model.Release{} authorised := admin.GetSession(r) != nil for _, release := range global.Releases { if !release.IsReleased() && !authorised { continue } releases = append(releases, release) } w.Header().Add("Content-Type", "application/json") err := json.NewEncoder(w).Encode(releases) if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } }) } func CreateRelease() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.NotFound(w, r) return } type PostReleaseBody struct { ID string `json:"id"` Title string `json:"title"` Description string `json:"description"` ReleaseType model.ReleaseType `json:"type"` ReleaseDate time.Time `json:"releaseDate"` Artwork string `json:"artwork"` Buyname string `json:"buyname"` Buylink string `json:"buylink"` } var data PostReleaseBody err := json.NewDecoder(r.Body).Decode(&data) if err != nil { http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) return } if global.GetRelease(data.ID) != nil { http.Error(w, fmt.Sprintf("Release %s already exists", data.ID), http.StatusBadRequest) return } var release = model.Release{ ID: data.ID, Title: data.Title, Description: data.Description, ReleaseType: data.ReleaseType, ReleaseDate: data.ReleaseDate, Artwork: data.Artwork, Buyname: data.Buyname, Buylink: data.Buylink, Links: []model.Link{}, Credits: []model.Credit{}, Tracks: []model.Track{}, } global.Releases = append([]model.Release{release}, global.Releases...) err = controller.CreateReleaseDB(global.DB, &release) if err != nil { fmt.Printf("Failed to create release %s: %s\n", release.ID, err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) err = json.NewEncoder(w).Encode(release) }) }