package lfo import ( "context" "net/http" core "nilfm.cc/git/nirvash/archetype" "strings" ) func WithAdapter(next http.Handler, adapter core.Adapter) http.Handler { 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) } 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) }