137 lines
3.6 KiB
Go
137 lines
3.6 KiB
Go
package httpx
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"log/slog"
|
|
"net/http"
|
|
"regexp"
|
|
"runtime/debug"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// instance names the process that answered, so a client behind the load
|
|
// balancer can tell the replicas apart.
|
|
func instance(id string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Writer.Header().Set("X-Instance-Id", id)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`)
|
|
|
|
// requestID keeps the X-Request-Id set by the load balancer, which overwrites
|
|
// any value a client sends; a malformed value is replaced, so a direct caller
|
|
// cannot inject into the logs.
|
|
func requestID(log *slog.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
id := c.GetHeader("X-Request-Id")
|
|
if !requestIDPattern.MatchString(id) {
|
|
id = newRequestID()
|
|
}
|
|
c.Set(keyRequestID, id)
|
|
c.Set(keyLogger, log)
|
|
c.Writer.Header().Set("X-Request-Id", id)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
func newRequestID() string {
|
|
var raw [16]byte
|
|
if _, err := rand.Read(raw[:]); err != nil {
|
|
panic("httpx: random source unavailable: " + err.Error())
|
|
}
|
|
return hex.EncodeToString(raw[:])
|
|
}
|
|
|
|
// accessLog writes one line per request at a level that follows the
|
|
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
|
|
// how much traffic is recorded. Headers, query strings and bodies are never
|
|
// recorded. time.Since uses the monotonic clock, so wall clock adjustments
|
|
// cannot distort the duration.
|
|
func accessLog() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
c.Next()
|
|
|
|
status := c.Writer.Status()
|
|
level := slog.LevelDebug
|
|
switch {
|
|
case status >= http.StatusInternalServerError:
|
|
level = slog.LevelError
|
|
case status >= http.StatusBadRequest:
|
|
level = slog.LevelInfo
|
|
}
|
|
log := logger(c)
|
|
ctx := c.Request.Context()
|
|
if !log.Enabled(ctx, level) {
|
|
return
|
|
}
|
|
attrs := []any{
|
|
"request_id", RequestID(c),
|
|
"method", c.Request.Method,
|
|
"path", c.Request.URL.Path,
|
|
"status", status,
|
|
"duration_ms", float64(time.Since(start).Microseconds()) / 1000,
|
|
"bytes", c.Writer.Size(),
|
|
}
|
|
if id, ok := UserID(c); ok {
|
|
attrs = append(attrs, "user_id", id.String())
|
|
}
|
|
log.Log(ctx, level, "request", attrs...)
|
|
}
|
|
}
|
|
|
|
// recovery turns a panic into a contract 500; the stack goes to the log only.
|
|
func recovery() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
logger(c).Error("panic recovered",
|
|
"request_id", RequestID(c),
|
|
"panic", fmt.Sprint(r),
|
|
"stack", string(debug.Stack()),
|
|
)
|
|
if !c.Writer.Written() {
|
|
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
|
}
|
|
c.Abort()
|
|
}
|
|
}()
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// Timeout bounds the whole request with one deadline: waiting for a pooled
|
|
// connection, SQL statements and session lookups all observe it, so a hung
|
|
// dependency ends in a 503 within d instead of holding the client.
|
|
func Timeout(d time.Duration) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
ctx, cancel := context.WithTimeout(c.Request.Context(), d)
|
|
defer cancel()
|
|
c.Request = c.Request.WithContext(ctx)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// bodyLimit caps request bodies; exceeding it surfaces from the JSON
|
|
// decoder as *http.MaxBytesError.
|
|
func bodyLimit(maxBytes int64) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// The authenticated binary handler installs its own 10 MiB limit.
|
|
if c.Request.Method == http.MethodPost && c.FullPath() == "/api/v1/chats/:chat_id/attachments" {
|
|
c.Next()
|
|
return
|
|
}
|
|
if c.Request.Body != nil {
|
|
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|