Files
butterfliu/internal/controller/song.go
lzw-723 4bc160284d
All checks were successful
Go CI / test-and-build (push) Successful in 11s
提取cover服务
2026-04-08 20:44:04 +08:00

75 lines
1.9 KiB
Go

package controller
import (
"butterfliu/internal/service"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
)
type SongController struct {
songService *service.SongService
coverService *service.CoverService
}
func NewSongController(songService *service.SongService, coverService *service.CoverService) *SongController {
return &SongController{songService: songService, coverService: coverService}
}
func (c *SongController) GetAllWithDetails(w http.ResponseWriter, r *http.Request) {
songs, err := c.songService.GetAllWithDetails()
if err != nil {
jsonError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse(w, songs, http.StatusOK)
}
func (c *SongController) GetByIDWithDetails(w http.ResponseWriter, r *http.Request) {
paramID := chi.URLParam(r, "id")
id, err := strconv.Atoi(paramID)
if err != nil {
http.Error(w, "无效的歌曲 ID", http.StatusBadRequest)
return
}
song, err := c.songService.GetByIDWithDetails(id)
if err != nil {
jsonError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonResponse(w, song, http.StatusOK)
}
func (c *SongController) Stream(w http.ResponseWriter, r *http.Request) {
paramID := chi.URLParam(r, "id")
id, err := strconv.Atoi(paramID)
if err != nil {
http.Error(w, "无效的歌曲 ID", http.StatusBadRequest)
return
}
mediaFile, err := c.songService.GetMediaFile(id)
if err != nil {
http.Error(w, "未找到该媒体文件", http.StatusNotFound)
return
}
http.ServeFile(w, r, mediaFile.Path)
}
func (c *SongController) Cover(w http.ResponseWriter, r *http.Request) {
paramID := chi.URLParam(r, "id")
id, err := strconv.Atoi(paramID)
if err != nil {
http.Error(w, "无效的歌曲 ID", http.StatusBadRequest)
return
}
coverPath, err := c.coverService.GetSongCover(id)
if err != nil {
http.Error(w, "获取封面异常", http.StatusNotFound)
return
}
http.ServeFile(w, r, coverPath)
}