79 lines
1.8 KiB
Go
79 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"path"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
bleve_http "github.com/blevesearch/bleve/http"
|
|
"github.com/gorilla/mux"
|
|
)
|
|
|
|
var rxExt = regexp.MustCompile(`[0-9]+`)
|
|
|
|
func (a *appData) buildRouter() http.Handler {
|
|
router := mux.NewRouter()
|
|
|
|
bleve_http.RegisterIndexName("album", a.index)
|
|
searchHandler := bleve_http.NewSearchHandler("album")
|
|
|
|
router.Handle("/api/search", searchHandler).Methods("POST")
|
|
|
|
router.Handle("/api/recents", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
albums, err := a.db.ByPurchaseDate()
|
|
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
enc := json.NewEncoder(w)
|
|
err = enc.Encode(albums)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
})).Methods("GET")
|
|
|
|
router.Handle("/api/albums/{id:[0-9]+}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
vars := mux.Vars(r)
|
|
var id uint64
|
|
var err error
|
|
var idStr string
|
|
var ok bool
|
|
if len(vars) != 0 {
|
|
idStr, ok = vars["id"]
|
|
if ok == true {
|
|
id, err = strconv.ParseUint(idStr, 10, 64)
|
|
}
|
|
}
|
|
|
|
if ok == false || err != nil {
|
|
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
albumUnsafe, err := a.db.Get(AlbumID(id))
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
|
|
album := *albumUnsafe
|
|
ext := path.Ext(album.CoverURL)
|
|
ext = strings.ToLower(rxExt.ReplaceAllString(ext, ""))
|
|
album.CoverURL = fmt.Sprintf("/covers/%d%s", album.ID, ext)
|
|
|
|
enc := json.NewEncoder(w)
|
|
if err := enc.Encode(album); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
})).Methods("GET")
|
|
|
|
router.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
|
|
|
|
return router
|
|
}
|