Initial implementation of lightmux-contrib, a sibling module to lightmux that hosts opinionated middlewares with one sub-package per middleware: - realip: resolves the originating client IP from CF-Connecting-IP, True-Client-IP, X-Real-IP, or X-Forwarded-For. Optional peer-CIDR allowlist via netip.Prefix. - requestlog: emits a structured http.request record (method, path, status, duration, client) per request via splinter. - recoverer: catches panics, wraps with errx under op "recoverer", logs with stack, and writes a 500 response. Each package exposes a single New(...) constructor returning func(http.Handler) http.Handler. The contrib module intentionally does not import lightmux — middlewares interoperate via the standard stdlib middleware shape. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
// Package requestlog emits a structured "http.request" record per request
|
|
// (method, path, status, duration, client) via splinter.
|
|
package requestlog
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.juancwu.dev/juancwu/splinter"
|
|
)
|
|
|
|
type statusRecorder struct {
|
|
http.ResponseWriter
|
|
status int
|
|
wrote bool
|
|
}
|
|
|
|
func (s *statusRecorder) WriteHeader(code int) {
|
|
if !s.wrote {
|
|
s.status = code
|
|
s.wrote = true
|
|
}
|
|
s.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (s *statusRecorder) Write(b []byte) (int, error) {
|
|
if !s.wrote {
|
|
s.status = http.StatusOK
|
|
s.wrote = true
|
|
}
|
|
return s.ResponseWriter.Write(b)
|
|
}
|
|
|
|
// New returns a request-logging middleware. Pass nil to use splinter.Default()
|
|
// resolved at request time; otherwise records flow through the supplied logger.
|
|
func New(l *splinter.Logger) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
next.ServeHTTP(rec, r)
|
|
if l == nil {
|
|
splinter.Info("http.request",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", rec.status,
|
|
"duration", time.Since(start),
|
|
"client", r.RemoteAddr,
|
|
)
|
|
return
|
|
}
|
|
l.Info("http.request",
|
|
"method", r.Method,
|
|
"path", r.URL.Path,
|
|
"status", rec.status,
|
|
"duration", time.Since(start),
|
|
"client", r.RemoteAddr,
|
|
)
|
|
})
|
|
}
|
|
}
|