aboutsummaryrefslogtreecommitdiff
path: root/pkg/handler/static/handler.go
blob: 0973d75ec8bf59c89111050112bb0f43368cb147 (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
package static

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

	"git.gabrielgio.me/cerrado/pkg/ext"
	"git.gabrielgio.me/cerrado/static"
)

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

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