nirvash/lfo/middleware.go

39 lines
1 KiB
Go
Raw Normal View History

package lfo
import (
2022-06-03 04:56:38 +00:00
"context"
"net/http"
core "nilfm.cc/git/nirvash/archetype"
"strings"
)
func WithAdapter(next http.Handler, adapter core.Adapter) http.Handler {
2022-06-03 04:56:38 +00:00
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
*req = *req.WithContext(context.WithValue(req.Context(), "adapter", adapter))
next.ServeHTTP(w, req)
}
return http.HandlerFunc(handlerFunc)
}
func EnsurePageData(next http.Handler, adapter core.Adapter) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
pageTitle := req.FormValue("title")
pageContent := req.FormValue("content")
newSlug := req.FormValue("slug")
if pageTitle == "" || pageContent == "" || (adapter.EditableSlugs() && newSlug == "") {
newUri := "/edit/"
slug := strings.Join(strings.Split(req.URL.Path, "/")[2:], "/")
newUri += slug
newUri += "?no-empty=1"
req.Method = http.MethodGet
http.Redirect(w, req, newUri, http.StatusSeeOther)
} else {
next.ServeHTTP(w, req)
}
}
return http.HandlerFunc(handlerFunc)
}