diff options
| author | Anhgelus Morhtuuzh <william@herges.fr> | 2025-10-02 18:22:34 +0200 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <william@herges.fr> | 2025-10-02 18:22:34 +0200 |
| commit | 1168ac60d3a22c0d354f291fd657ad302df6ec05 (patch) | |
| tree | fc492948f751db0a72ec4a5ea1231b35d78c5b66 /backend | |
| parent | dfca0f5bbebfe11d9c5d8bf6584bd1bf80d62274 (diff) | |
feat(backend): use httplog
Diffstat (limited to 'backend')
| -rw-r--r-- | backend/data.go | 6 | ||||
| -rw-r--r-- | backend/router.go | 34 |
2 files changed, 34 insertions, 6 deletions
diff --git a/backend/data.go b/backend/data.go index e1a8478..bc74ba5 100644 --- a/backend/data.go +++ b/backend/data.go @@ -25,13 +25,11 @@ func (d *data) handleGeneric(w http.ResponseWriter, name string) { }, }).ParseFS(templates, fmt.Sprintf("templates/%s.html", name), "templates/base.html") if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return + panic(err) } err = t.ExecuteTemplate(w, "base.html", d) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - return + panic(err) } } diff --git a/backend/router.go b/backend/router.go index b1efea8..8ed63fa 100644 --- a/backend/router.go +++ b/backend/router.go @@ -3,22 +3,52 @@ package backend import ( "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() *chi.Mux { +func NewRouter(debug bool) *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(middleware.Logger) + 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{}, + })) return r } |
