dumb/handlers/handler.go

63 lines
1.9 KiB
Go
Raw Normal View History

2024-03-06 20:53:29 +01:00
package handlers
import (
"context"
"io"
"mime"
2024-03-06 20:53:29 +01:00
"net/http"
"os"
"path"
"strings"
2024-03-06 20:53:29 +01:00
"github.com/a-h/templ"
2024-05-01 22:22:54 +01:00
gorillaHandlers "github.com/gorilla/handlers"
2024-03-06 20:53:29 +01:00
"github.com/gorilla/mux"
2024-05-02 21:29:50 +01:00
"github.com/rramiachraf/dumb/utils"
2024-03-06 20:53:29 +01:00
"github.com/rramiachraf/dumb/views"
)
2024-05-02 21:29:50 +01:00
func New(logger *utils.Logger) *mux.Router {
2024-03-06 20:53:29 +01:00
r := mux.NewRouter()
r.Use(utils.MustHeaders)
2024-05-01 21:06:03 +01:00
r.Use(gorillaHandlers.CompressHandler)
2024-03-06 20:53:29 +01:00
r.Handle("/", templ.Handler(views.HomePage()))
2024-05-01 22:22:54 +01:00
r.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("User-agent: *\nDisallow: /\n"))
})
2024-03-06 20:53:29 +01:00
r.HandleFunc("/albums/{artist}/{albumName}", album(logger)).Methods("GET")
r.HandleFunc("/images/{filename}.{ext}", imageProxy(logger)).Methods("GET")
r.HandleFunc("/search", search(logger)).Methods("GET")
2024-04-06 00:14:51 -06:00
r.HandleFunc("/{annotation-id}/{artist-song}/{verse}/annotations", annotations(logger)).Methods("GET")
2024-03-06 20:53:29 +01:00
r.HandleFunc("/instances.json", instances(logger)).Methods("GET")
r.PathPrefix("/static/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
url := strings.Replace(r.URL.Path, "/static", "static", 1)
f, err := os.Open(url)
if err != nil {
w.WriteHeader(http.StatusNotFound)
views.ErrorPage(http.StatusNotFound, "page not found")
return
}
defer f.Close()
mimeType := mime.TypeByExtension(path.Ext(r.URL.Path))
w.Header().Set("content-type", mimeType)
if _, err := io.Copy(w, f); err != nil {
logger.Error(err.Error())
}
})
2024-04-06 00:14:51 -06:00
r.PathPrefix("/{annotation-id}/{artist-song}-lyrics").HandlerFunc(lyrics(logger)).Methods("GET")
r.PathPrefix("/{annotation-id}/{artist-song}").HandlerFunc(lyrics(logger)).Methods("GET")
r.PathPrefix("/{annotation-id}").HandlerFunc(lyrics(logger)).Methods("GET")
2024-03-06 20:53:29 +01:00
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
views.ErrorPage(404, "page not found").Render(context.Background(), w)
})
return r
}