aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/static/handler.go
blob: 6cc884ea1370a2a0268e04ed70a75e4f978c7c9f (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package static

import (
	"bytes"
	"fmt"
	"io"
	"io/fs"
	"mime"
	"net/http"
	"path/filepath"

	"git.gabrielgio.me/cerrado/pkg/ext"
	"git.gabrielgio.me/cerrado/static"
	"github.com/alecthomas/chroma/v2"
	"github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/alecthomas/chroma/v2/styles"
)

func ServeStaticHandler() (ext.ErrorRequestHandler, error) {
	staticFs, err := fs.Sub(static.Static, ".")
	if err != nil {
		return nil, err
	}

	return func(w http.ResponseWriter, r *ext.Request) error {
		var (
			f = r.PathValue("file")
			e = filepath.Ext(f)
			m = mime.TypeByExtension(e)
		)
		ext.SetMIME(w, m)
		w.Header().Add("Cache-Control", "max-age=31536000")
		http.ServeFileFS(w, r.Request, staticFs, f)
		return nil
	}, nil
}

func ServeStaticCSSHandler(lightTheme, darkTheme string) (ext.ErrorRequestHandler, error) {
	var (
		lightStyle = styles.Get(lightTheme)
		darkStyle  = styles.Get(darkTheme)
		formatter  = html.New(
			html.WithCSSComments(false),
		)
	)

	return func(w http.ResponseWriter, r *ext.Request) error {
		ext.SetMIME(w, "text/css")
		w.Header().Add("Cache-Control", "max-age=31536000")

		// use buffer so this function can fail before writing to http.ResponseWriter
		var buffer bytes.Buffer

		var style *chroma.Style
		style = darkStyle
		buffer.Write([]byte("[data-bs-theme=\"dark\"] {\n"))
		err := formatter.WriteCSS(&ws{&buffer}, style)
		if err != nil {
			return err
		}
		buffer.Write([]byte("}\n"))

		style = lightStyle
		buffer.Write([]byte("[data-bs-theme=\"light\"] {\n"))
		err = formatter.WriteCSS(&ws{&buffer}, style)
		if err != nil {
			return err
		}
		buffer.Write([]byte("}"))

		_, err = io.Copy(w, &buffer)
		if err != nil {
			return err
		}

		return nil
	}, nil
}

type ws struct {
	inner io.Writer
}

// This is very cursed, and rely on the fact that it writes every css rule at time.
// it adds & to the begging so it can be nested by the ServeStaticCSSHandler.
// This will allow the follow bootstrap data-bs-theme.
func (w *ws) Write(p []byte) (n int, err error) {
	return fmt.Fprintf(w.inner, "& %s", string(p))
}