blog/router/router.go

94 lines
2.1 KiB
Go

package router
import (
"fmt"
"net/http"
"path/filepath"
"go.jolheiser.com/blog/post"
"go.jolheiser.com/blog/static"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/rs/zerolog/log"
)
func New(blog *post.Blog) *chi.Mux {
m := chi.NewMux()
m.Use(middleware.Logger)
m.Use(middleware.Recoverer)
m.Get("/", indexHandler(blog))
m.Route("/{post}", func(r chi.Router) {
r.With(slashesMiddleware).Get("/", fileHandler(blog))
r.Get("/{asset}", assetHandler(blog))
})
m.Route("/_", func(r chi.Router) {
r.Get("/sakura.css", static.SakuraCSS)
})
return m
}
func indexHandler(blog *post.Blog) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := static.IndexTemplate.Execute(w, blog); err != nil {
log.Error().Err(err).Msg("could not execute template")
}
}
}
func fileHandler(blog *post.Blog) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
postName := chi.URLParam(r, "post")
p, ok := blog.Post(postName)
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
if err := static.PostTemplate.Execute(w, p); err != nil {
log.Error().Err(err).Msg("could not execute template")
}
}
}
func assetHandler(blog *post.Blog) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
postName := chi.URLParam(r, "post")
p, ok := blog.Post(postName)
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
assetName := chi.URLParam(r, "asset")
apn := filepath.Join(filepath.Dir(p.Path), assetName)
http.ServeFile(w, r, apn)
}
}
func slashesMiddleware(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
var path string
rctx := chi.RouteContext(r.Context())
if rctx != nil && rctx.RoutePath != "" {
path = rctx.RoutePath
} else {
path = r.URL.Path
}
if len(path) > 1 && path[len(path)-1] != '/' {
path += "/"
if r.URL.RawQuery != "" {
path = fmt.Sprintf("%s?%s", path, r.URL.RawQuery)
}
redirectURL := fmt.Sprintf("//%s%s", r.Host, path)
http.Redirect(w, r, redirectURL, 301)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}