51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package router
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"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.Get("/{post}", fileHandler(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")
|
|
}
|
|
}
|
|
}
|