Files
summercms/surf/bodylimit.go
Jakub Zych 30539b954f feat(06-03): add path-scoped CORS and per-route body limits
- CORS matches Laravel path globs (api/* includes nested segments); unlisted paths get no headers
- Non-raw routes wrap http.MaxBytesReader from http.body_limits.default_bytes; body.limit:N overrides innermost
- Raw routes stay uncapped at this layer
2026-09-19 20:10:02 +02:00

47 lines
924 B
Go

package surf
import (
"fmt"
"net/http"
"strconv"
"strings"
)
func bodyLimit(n int64) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if n > 0 && r.Body != nil {
r.Body = http.MaxBytesReader(w, r.Body, n)
}
next.ServeHTTP(w, r)
})
}
}
func parseBodyLimit(param string) (int64, error) {
n, err := strconv.ParseInt(param, 10, 64)
if err != nil || n <= 0 {
return 0, fmt.Errorf("invalid body.limit %q", param)
}
return n, nil
}
func routeBodyLimit(rt route, defaultBytes int64) (int64, error) {
if rt.raw {
return 0, nil
}
limit := defaultBytes
for _, name := range rt.middleware {
base, param, ok := strings.Cut(name, ":")
if !ok || base != "body.limit" {
continue
}
n, err := parseBodyLimit(param)
if err != nil {
return 0, err
}
limit = n
}
return limit, nil
}