Files
go-kite/middleware/logger.go
Timo Riegebauer ae5d1f610a feat: middleware reach, response writer interfaces, and CORS fixes
- Run global middleware for all requests, including OPTIONS preflights, NotFound, and MethodNotAllowed — previously bypassed by httprouter's internal handling
- Implement Hijacker, Flusher, and Pusher on the response writer for WebSocket, SSE, and HTTP/2 push support
- Fix CORS: echo a single matching origin, handle AllowCredentials with wildcard, append Vary: Origin
- Logger logs from a defer to capture correct status on panicked requests
- Static and StaticFS accept route middleware; add Context.AddHeader; warn on NotFound handler override
2026-05-17 17:51:56 +02:00

52 lines
1.1 KiB
Go

package middleware
import (
"fmt"
"io"
"log"
"os"
"time"
"git.trcreatives.at/trcreatives/go-kite"
)
type LoggerConfig struct {
Output io.Writer
Format func(method, path string, statusCode int, latency time.Duration) string
Skip func(ctx *kite.Context) bool
}
func DefaultLoggerFormat(method, path string, statusCode int, latency time.Duration) string {
return fmt.Sprintf("[Kite] %s %s -> %d in %s", method, path, statusCode, latency)
}
func Logger() kite.Middleware {
return LoggerWithConfig(LoggerConfig{})
}
func LoggerWithConfig(cfg LoggerConfig) kite.Middleware {
if cfg.Output == nil {
cfg.Output = os.Stdout
}
if cfg.Format == nil {
cfg.Format = DefaultLoggerFormat
}
logger := log.New(cfg.Output, "", log.LstdFlags)
return func(h kite.Handler) kite.Handler {
return func(ctx *kite.Context) error {
if cfg.Skip != nil && cfg.Skip(ctx) {
return h(ctx)
}
start := time.Now()
defer func() {
logger.Println(cfg.Format(ctx.GetMethod(), ctx.GetPath(), ctx.GetStatusCode(), time.Since(start)))
}()
return h(ctx)
}
}
}