arimelody-web/admin/music/trackhttp.go
ari melody 21912d4ec2
refactor mux path routes
legend has it that if you refactor your code enough times, one day you
will finally be happy
2025-11-07 17:48:06 +00:00

79 lines
2.7 KiB
Go

package music
import (
"fmt"
"net/http"
"os"
"arimelody-web/admin/core"
"arimelody-web/admin/templates"
"arimelody-web/controller"
"arimelody-web/model"
)
func serveTracks(app *model.AppState) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
tracks, err := controller.GetAllTracks(app.DB)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to fetch tracks: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
type TracksResponse struct {
core.AdminPageData
Tracks []*model.Track
}
err = templates.TracksTemplate.Execute(w, TracksResponse{
AdminPageData: core.AdminPageData{ Path: r.URL.Path, Session: session },
Tracks: tracks,
})
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to serve admin tracks page: %s\n", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
})
}
func serveTrack(app *model.AppState, trackID string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value("session").(*model.Session)
track, err := controller.GetTrack(app.DB, trackID)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to serve admin track page for %s: %s\n", trackID, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if track == nil {
http.NotFound(w, r)
return
}
releases, err := controller.GetTrackReleases(app.DB, track.ID, true)
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to fetch releases for track %s: %s\n", trackID, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
type TrackResponse struct {
core.AdminPageData
Track *model.Track
Releases []*model.Release
}
err = templates.EditTrackTemplate.Execute(w, TrackResponse{
AdminPageData: core.AdminPageData{ Path: r.URL.Path, Session: session },
Track: track,
Releases: releases,
})
if err != nil {
fmt.Fprintf(os.Stderr, "WARN: Failed to serve admin track page for %s: %s\n", trackID, err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
})
}