2021-09-03 04:31:27 +00:00
|
|
|
package router
|
|
|
|
|
|
|
|
import (
|
2022-07-07 05:05:18 +00:00
|
|
|
"net"
|
2021-09-03 04:31:27 +00:00
|
|
|
"net/http"
|
2021-12-26 05:13:57 +00:00
|
|
|
|
2021-09-03 04:31:27 +00:00
|
|
|
"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))
|
2022-07-07 05:05:18 +00:00
|
|
|
m.Route("/_", func(r chi.Router) {
|
|
|
|
r.Get("/reload", reloadHandler(blog))
|
|
|
|
r.Get("/sakura.css", static.SakuraCSS)
|
|
|
|
})
|
2021-09-03 04:31:27 +00:00
|
|
|
|
|
|
|
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")
|
2022-07-07 05:05:18 +00:00
|
|
|
p, ok := blog.Post(postName)
|
2021-09-03 04:31:27 +00:00
|
|
|
if !ok {
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-07-07 05:05:18 +00:00
|
|
|
if err := static.PostTemplate.Execute(w, map[string]interface{}{
|
|
|
|
"Post": p,
|
|
|
|
}); err != nil {
|
|
|
|
log.Error().Err(err).Msg("could not execute template")
|
2021-12-26 05:13:57 +00:00
|
|
|
}
|
2022-07-07 05:05:18 +00:00
|
|
|
}
|
|
|
|
}
|
2021-12-26 05:13:57 +00:00
|
|
|
|
2022-07-07 05:05:18 +00:00
|
|
|
func reloadHandler(blog *post.Blog) http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
2021-12-26 05:13:57 +00:00
|
|
|
if err != nil {
|
2022-07-07 05:05:18 +00:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2021-12-26 05:13:57 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-07-07 05:05:18 +00:00
|
|
|
ip := net.ParseIP(host)
|
|
|
|
if ip == nil || !ip.IsLoopback() {
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2021-09-03 04:31:27 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-07-07 05:05:18 +00:00
|
|
|
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")
|
2021-09-03 04:31:27 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|