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) 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 FormMapToBuildOptions(next http.Handler) http.Handler { handlerFunc := func(w http.ResponseWriter, req *http.Request) { options := make(map[core.BuildOption]string) for k, arr := range req.PostForm { v := strings.Join(arr, "") optNameAndType := strings.Split(k, ":") optName := optNameAndType[0] optType := optNameAndType[1] options[core.BuildOption{ Name: optName, Type: optType, }] = v } *req = *req.WithContext(context.WithValue(req.Context(), "build-options", options)) next.ServeHTTP(w, req) } return http.HandlerFunc(handlerFunc) } func PrepareForUpload(next http.Handler, fileManager core.FileManager) http.Handler { handlerFunc := func(w http.ResponseWriter, req *http.Request) { req.ParseMultipartForm(fileManager.MaxUploadMB() << 20) next.ServeHTTP(w, req) } return http.HandlerFunc(handlerFunc) }