From 3bf802c9c24e67f1a3c413db2d18145857268f02 Mon Sep 17 00:00:00 2001 From: rramiachraf <51409801+rramiachraf@users.noreply.github.com> Date: Tue, 11 Jun 2024 20:42:33 +0100 Subject: [PATCH] refactor: organize routing a bit --- handlers/handler.go | 35 ++++++++++++++++++++++++++++------- views/album.templ | 2 +- views/artist.templ | 2 +- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/handlers/handler.go b/handlers/handler.go index 9cb32c7..fd0cceb 100644 --- a/handlers/handler.go +++ b/handlers/handler.go @@ -11,26 +11,47 @@ import ( "github.com/rramiachraf/dumb/views" ) +type route struct { + Path string + Handler func(*utils.Logger) http.HandlerFunc + Method string +} + func New(logger *utils.Logger, staticFiles static) *mux.Router { r := mux.NewRouter() r.Use(utils.MustHeaders) r.Use(gorillaHandlers.CompressHandler) + routes := []route{ + {Path: "/albums/{artist}/{albumName}", Handler: album}, + {Path: "/artists/{artist}", Handler: artist}, + {Path: "/images/{filename}.{ext}", Handler: imageProxy}, + {Path: "/search", Handler: search}, + {Path: "/{annotation-id}/{artist-song}/{verse}/annotations", Handler: annotations}, + {Path: "/instances.json", Handler: instances}, + } + + for _, rr := range routes { + method := rr.Method + if method == "" { + method = http.MethodGet + } + + r.HandleFunc(rr.Path, rr.Handler(logger)).Methods(method) + } + + r.PathPrefix("/static/").HandlerFunc(staticAssets(logger, staticFiles)) + r.Handle("/", templ.Handler(views.HomePage())) r.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("User-agent: *\nDisallow: /\n")) }) - r.HandleFunc("/albums/{artist}/{albumName}", album(logger)).Methods("GET") - r.HandleFunc("/artists/{artist}", artist(logger)).Methods("GET") - r.HandleFunc("/images/{filename}.{ext}", imageProxy(logger)).Methods("GET") - r.HandleFunc("/search", search(logger)).Methods("GET") - r.HandleFunc("/{annotation-id}/{artist-song}/{verse}/annotations", annotations(logger)).Methods("GET") - r.HandleFunc("/instances.json", instances(logger)).Methods("GET") - r.PathPrefix("/static/").HandlerFunc(staticAssets(logger, staticFiles)) + 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") + 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) diff --git a/views/album.templ b/views/album.templ index bbb68ba..c0e6df5 100644 --- a/views/album.templ +++ b/views/album.templ @@ -6,7 +6,7 @@ import ( ) templ AlbumPage(a data.Album) { - @layout(fmt.Sprintf("%s - %s", a.Artist, a.Name)) { + @layout(fmt.Sprintf("%s - %s", a.Artist.Name, a.Name)) {
{ album.Name }