blog/router/router.go

79 lines
1.7 KiB
Go
Raw Normal View History

package router
import (
"net"
"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("/reload", reloadHandler(blog))
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, map[string]interface{}{
"Blog": 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, map[string]interface{}{
"Post": p,
}); err != nil {
log.Error().Err(err).Msg("could not execute template")
}
}
}
func reloadHandler(blog *post.Blog) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
w.WriteHeader(http.StatusUnauthorized)
return
}
log.Info().Msg("reloading posts")
if err := blog.Scan(); err != nil {
http.Error(w, "could not re-scan", http.StatusInternalServerError)
log.Error().Err(err).Msg("could not re-scan")
}
}
}