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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
package backend
import (
"context"
"embed"
"io/fs"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httplog/v3"
)
const Version = "0.1.0"
//go:embed templates
var templates embed.FS
func NewRouter(debug bool, cfg *Config) *chi.Mux {
logFormat := httplog.SchemaECS.Concise(!debug)
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: logFormat.ReplaceAttr,
})).With(
slog.String("app", "anhgelus/small-web"),
slog.String("version", Version),
)
logLevel := slog.LevelWarn
if debug {
logLevel = slog.LevelDebug
}
r := chi.NewRouter()
r.Use(middleware.Timeout(30 * time.Second))
r.Use(httplog.RequestLogger(logger, &httplog.Options{
Level: logLevel,
// Set log output to Elastic Common Schema (ECS) format.
Schema: logFormat,
RecoverPanics: true,
Skip: func(req *http.Request, respStatus int) bool {
return respStatus == http.StatusNotFound || respStatus == http.StatusMethodNotAllowed
},
// Optionally, log selected request/response headers explicitly.
LogRequestHeaders: []string{"Origin"},
LogResponseHeaders: []string{},
}))
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), "config", cfg)
next.ServeHTTP(w, r.WithContext(ctx))
})
})
return r
}
// httpEmbedFS is an implementation of fs.FS, fs.ReadDirFS and fs.ReadFileFS helping to manage embed.FS for http server
type httpEmbedFS struct {
embed.FS
prefix string
}
func (h *httpEmbedFS) Open(name string) (fs.File, error) {
return h.FS.Open(h.prefix + "/" + name)
}
func (h *httpEmbedFS) ReadFile(name string) ([]byte, error) {
return h.FS.ReadFile(h.prefix + "/" + name)
}
func (h *httpEmbedFS) ReadDir(name string) ([]fs.DirEntry, error) {
return h.FS.ReadDir(h.prefix + "/" + name)
}
// UsableEmbedFS converts embed.FS into usable fs.FS by Golatt
//
// folder may not finish or start with a slash (/)
func UsableEmbedFS(folder string, em embed.FS) fs.FS {
return &httpEmbedFS{
prefix: folder,
FS: em,
}
}
func HandleStaticFiles(r *chi.Mux, path string, root fs.FS) {
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, req *http.Request) {
ctx := chi.RouteContext(req.Context())
pathPrefix := strings.TrimSuffix(ctx.RoutePattern(), "/*")
if pathPrefix+"/" == req.URL.Path {
r.NotFoundHandler().ServeHTTP(w, req)
return
}
http.StripPrefix(pathPrefix, http.FileServerFS(root)).ServeHTTP(w, req)
})
}
|