dumb/handlers/handler.go

77 lines
2.2 KiB
Go
Raw Permalink Normal View History

2024-03-06 20:53:29 +01:00
package handlers
import (
"net/http"
"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-06-11 20:42:33 +01:00
type route struct {
2024-06-12 18:30:29 +01:00
Path string
Handler func(*utils.Logger) http.HandlerFunc
Method string
Template func() templ.Component
2024-06-11 20:42:33 +01:00
}
2024-05-03 14:47:57 +01:00
func New(logger *utils.Logger, staticFiles static) *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
2024-06-11 20:42:33 +01:00
routes := []route{
2024-06-12 18:30:29 +01:00
{Path: "/", Template: views.HomePage},
{Path: "/robots.txt", Handler: robotsHandler},
2024-06-11 20:42:33 +01:00
{Path: "/albums/{artist}/{albumName}", Handler: album},
{Path: "/artists/{artist}", Handler: artist},
2024-06-23 16:38:53 -06:00
{Path: "/a/{article}", Handler: article},
2024-06-11 20:42:33 +01:00
{Path: "/images/{filename}.{ext}", Handler: imageProxy},
{Path: "/search", Handler: search},
{Path: "/{annotation-id}/{artist-song}/{verse}/annotations", Handler: annotations},
{Path: "/{annotation-id}/{artist-song}/annotations", Handler: annotations},
2024-06-11 20:42:33 +01:00
{Path: "/instances.json", Handler: instances},
}
2024-06-12 18:30:29 +01:00
registerRoutes(r, routes, logger)
2024-06-11 20:42:33 +01:00
r.PathPrefix("/static/").HandlerFunc(staticAssets(logger, staticFiles))
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-06-11 20:42:33 +01:00
2024-03-06 20:53:29 +01:00
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
2024-07-14 00:43:06 +01:00
utils.RenderTemplate(w, views.ErrorPage(404, "page not found"), logger)
2024-03-06 20:53:29 +01:00
})
return r
}
2024-06-12 18:30:29 +01:00
func robotsHandler(l *utils.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, err := w.Write([]byte("User-agent: *\nDisallow: /\n")); err != nil {
l.Error(err.Error())
}
}
}
func registerRoutes(router *mux.Router, routes []route, logger *utils.Logger) {
for _, r := range routes {
method := r.Method
if method == "" {
method = http.MethodGet
}
if r.Template != nil {
router.Handle(r.Path, templ.Handler(r.Template())).Methods(method)
continue
}
router.HandleFunc(r.Path, r.Handler(logger)).Methods(method)
}
}