all repos — nirvash @ 8fdc9ddb460f6dc76363da7c64bdae15927bf430

modular CMS using the quartzgun library

lfo/middleware.go (raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 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)
}