nirvash/lfo/middleware.go

98 lines
2.8 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 WithFileManager(next http.Handler, fileManager core.FileManager) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
*req = *req.WithContext(context.WithValue(req.Context(), "file-manager", fileManager))
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)
}
2022-06-08 05:44:54 +00:00
func SanitizeFormMap(next http.Handler) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
delete(req.PostForm, "csrfToken")
next.ServeHTTP(w, req)
}
return http.HandlerFunc(handlerFunc)
}
func FormMapToAdapterConfig(next http.Handler, adapter core.Adapter) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
cfg := make(map[core.ConfigOption]string)
for k, arr := range req.PostForm {
v := strings.Join(arr, "")
optNameAndType := strings.Split(k, ":")
optName := optNameAndType[0]
optType := optNameAndType[1]
cfg[core.ConfigOption{
Name: optName,
Type: optType,
}] = v
}
*req = *req.WithContext(context.WithValue(req.Context(), "config", cfg))
next.ServeHTTP(w, req)
}
return http.HandlerFunc(handlerFunc)
}
func WithFileData(next http.Handler, fileManager core.FileManager) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
fileSlug := ctx.Value("params").(map[string]string)["Slug"]
fileData := fileManager.GetFileData(fileSlug)
*req = *req.WithContext(context.WithValue(req.Context(), "file-data", fileData))
next.ServeHTTP(w, req)
}
return http.HandlerFunc(handlerFunc)
}
2022-06-13 06:32:14 +00:00
func PrepareForUpload(next http.Handler) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
req.ParseMultipartForm(250 << 20)
next.ServeHTTP(w, req)
}
return http.HandlerFunc(handlerFunc)
}