-
Notifications
You must be signed in to change notification settings - Fork 0
/
song.go
60 lines (48 loc) · 1.28 KB
/
song.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package handlers
import (
"net/http"
"strconv"
"github.com/go-chi/chi"
"github.com/rramiachraf/chorus/database"
)
func GetSongs(w http.ResponseWriter, r *http.Request) {
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
s, err := database.GetSongs(page)
if err != nil {
HandleError(w, http.StatusInternalServerError, err, "error while fetching songs")
return
}
WriteJSON(w, http.StatusOK, paginate(s, 20, page))
}
func GetSong(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
HandleError(w, http.StatusBadRequest, err, "invalid song id")
return
}
s, err := database.GetSong(id)
if err != nil {
HandleError(w, http.StatusNotFound, err, "song not found")
return
}
WriteJSON(w, http.StatusOK, s)
}
func ListenToSong(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(chi.URLParam(r, "id"))
if err != nil {
HandleError(w, http.StatusBadRequest, err, "invalid song id")
return
}
path, err := database.GetSongPath(id)
if err != nil {
HandleError(w, http.StatusNotFound, err, "song not found")
return
}
http.ServeFile(w, r, path)
}
func GetRandomSong(w http.ResponseWriter, r *http.Request) {
id := database.GetRandomSong()
WriteJSON(w, http.StatusOK, map[string]int{
"id": id,
})
}