Implements a basic main function
This commit is contained in:
78
router.go
Normal file
78
router.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
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) {
|
||||
a.dbLock <- true
|
||||
albums, err := a.db.ByPurchaseDate()
|
||||
<-a.dbLock
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
a.dbLock <- true
|
||||
album, err := a.db.Get(AlbumID(id))
|
||||
<-a.dbLock
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
//sanitize extension of the path from bedetheque.com
|
||||
ext := path.Ext(album.CoverURL)
|
||||
rxExt.ReplaceAllString(ext, "")
|
||||
album.CoverURL = fmt.Sprintf("/covers/%d%s", album.ID, ext)
|
||||
|
||||
enc := json.NewEncoder(w)
|
||||
if err := enc.Encode(a); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
})).Methods("GET")
|
||||
|
||||
return router
|
||||
}
|
||||
Reference in New Issue
Block a user