Compare commits

...
Author SHA1 Message Date
dependabot[bot] 34151a1012 build(deps): bump github.com/go-chi/chi/v5 from 5.3.2 to 5.4.0
Bumps [github.com/go-chi/chi/v5](https://github.com/go-chi/chi) from 5.3.2 to 5.4.0.
- [Release notes](https://github.com/go-chi/chi/releases)
- [Changelog](https://github.com/go-chi/chi/blob/master/CHANGELOG.md)
- [Commits](https://github.com/go-chi/chi/compare/v5.3.2...v5.4.0)

---
updated-dependencies:
- dependency-name: github.com/go-chi/chi/v5
  dependency-version: 5.4.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 10:42:13 +00:00
16 changed files with 240 additions and 125 deletions

No files matched your search

+1 -1
View File
@@ -22,7 +22,7 @@ require (
github.com/egirna/icap-client v0.1.1
github.com/gabriel-vasile/mimetype v1.4.15
github.com/ggwhite/go-masker v1.1.0
github.com/go-chi/chi/v5 v5.3.2
github.com/go-chi/chi/v5 v5.4.0
github.com/go-chi/httprate v0.16.1
github.com/go-chi/render v1.0.3
github.com/go-ldap/ldap/v3 v3.4.15
+2 -2
View File
@@ -286,8 +286,8 @@ github.com/go-asn1-ber/asn1-ber v1.3.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkPro
github.com/go-asn1-ber/asn1-ber v1.4.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-chi/chi/v5 v5.4.0 h1:+ufzvFTGKyin26Or5DLrlIDq4ygIDBVcj7oVNeeaYFE=
github.com/go-chi/chi/v5 v5.4.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4=
+43 -43
View File
@@ -368,50 +368,50 @@ with `net/http` can be used with chi's mux.
| [WithValue] | Short-hand middleware to set a key/value on the request context |
----------------------------------------------------------------------------------------------------
[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentEncoding
[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/middleware#AllowContentType
[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/middleware#BasicAuth
[Compress]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compress
[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ContentCharset
[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/middleware#CleanPath
[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetHead
[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetReqID
[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Heartbeat
[Logger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Logger
[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/middleware#NoCache
[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Profiler
[ClientIPFromHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromHeader
[ClientIPFromXFF]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromXFF
[ClientIPFromXFFTrustedProxies]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromXFFTrustedProxies
[ClientIPFromRemoteAddr]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ClientIPFromRemoteAddr
[GetClientIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetClientIP
[GetClientIPAddr]: https://pkg.go.dev/github.com/go-chi/chi/middleware#GetClientIPAddr
[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RealIP
[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Recoverer
[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RedirectSlashes
[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestLogger
[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RequestID
[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/middleware#RouteHeaders
[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/middleware#SetHeader
[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/middleware#StripSlashes
[AllowContentEncoding]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#AllowContentEncoding
[AllowContentType]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#AllowContentType
[BasicAuth]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#BasicAuth
[Compress]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Compress
[ContentCharset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ContentCharset
[CleanPath]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#CleanPath
[GetHead]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetHead
[GetReqID]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetReqID
[Heartbeat]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Heartbeat
[Logger]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Logger
[NoCache]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#NoCache
[Profiler]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Profiler
[ClientIPFromHeader]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromHeader
[ClientIPFromXFF]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFF
[ClientIPFromXFFTrustedProxies]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromXFFTrustedProxies
[ClientIPFromRemoteAddr]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ClientIPFromRemoteAddr
[GetClientIP]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetClientIP
[GetClientIPAddr]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#GetClientIPAddr
[RealIP]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RealIP
[Recoverer]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Recoverer
[RedirectSlashes]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RedirectSlashes
[RequestLogger]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RequestLogger
[RequestID]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RequestID
[RouteHeaders]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#RouteHeaders
[SetHeader]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#SetHeader
[StripSlashes]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#StripSlashes
[Sunset]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Sunset
[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Throttle
[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleBacklog
[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleWithOpts
[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Timeout
[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/middleware#URLFormat
[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithLogEntry
[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WithValue
[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/middleware#Compressor
[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#DefaultLogFormatter
[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/middleware#EncoderFunc
[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRoute
[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#HeaderRouter
[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogEntry
[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LogFormatter
[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/middleware#LoggerInterface
[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/middleware#ThrottleOpts
[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/middleware#WrapResponseWriter
[Throttle]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Throttle
[ThrottleBacklog]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleBacklog
[ThrottleWithOpts]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleWithOpts
[Timeout]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Timeout
[URLFormat]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#URLFormat
[WithLogEntry]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WithLogEntry
[WithValue]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WithValue
[Compressor]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#Compressor
[DefaultLogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#DefaultLogFormatter
[EncoderFunc]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#EncoderFunc
[HeaderRoute]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#HeaderRoute
[HeaderRouter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#HeaderRouter
[LogEntry]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LogEntry
[LogFormatter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LogFormatter
[LoggerInterface]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#LoggerInterface
[ThrottleOpts]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#ThrottleOpts
[WrapResponseWriter]: https://pkg.go.dev/github.com/go-chi/chi/v5/middleware#WrapResponseWriter
### Choosing a ClientIP middleware
+9 -7
View File
@@ -2,7 +2,7 @@
//
// chi supports the four most recent major versions of Go.
//
// Example:
// # Example
//
// package main
//
@@ -25,11 +25,13 @@
// http.ListenAndServe(":3333", r)
// }
//
// See github.com/go-chi/chi/_examples/ for more in-depth examples.
// See [github.com/go-chi/chi/v5/_examples] for more in-depth examples.
//
// # URL patterns
//
// URL patterns allow for easy matching of path components in HTTP
// requests. The matching components can then be accessed using
// chi.URLParam(). All patterns must begin with a slash.
// [chi.URLParam](). All patterns must begin with a slash.
//
// A simple named placeholder {name} matches any sequence of characters
// up to the next / or the end of the URL. Trailing slashes on paths must
@@ -37,11 +39,11 @@
//
// A placeholder with a name followed by a colon allows a regular
// expression match, for example {number:\\d+}. The regular expression
// syntax is Go's normal regexp RE2 syntax, except that / will never be
// matched. An anonymous regexp pattern is allowed, using an empty string
// before the colon in the placeholder, such as {:\\d+}
// syntax is Go's normal [regexp] RE2 syntax (see [regexp/syntax]), except
// that / will never be matched. An anonymous regexp pattern is allowed, using
// an empty string before the colon in the placeholder, such as {:\\d+}.
//
// The special placeholder of asterisk matches the rest of the requested
// The special placeholder of asterisk (*) matches the rest of the requested
// URL. Any trailing characters in the pattern are ignored. This is the only
// placeholder which will match / characters.
//
+31 -7
View File
@@ -3,15 +3,13 @@ package chi
import (
"context"
"net/http"
"slices"
"strings"
)
// URLParam returns the url parameter from a http.Request object.
func URLParam(r *http.Request, key string) string {
if rctx := RouteContext(r.Context()); rctx != nil {
return rctx.URLParam(key)
}
return ""
return URLParamFromCtx(r.Context(), key)
}
// URLParamFromCtx returns the url parameter from a http.Request Context.
@@ -42,6 +40,8 @@ var (
// Context is the default routing context set on the root node of a
// request context to track route patterns, URL parameters and
// an optional routing path.
//
// NOTE: New reference fields (slices, maps, pointers) must be deep-copied in Clone.
type Context struct {
Routes Routes
@@ -95,12 +95,36 @@ func (x *Context) Reset() {
x.parentCtx = nil
}
// Clone a routing context so that it may be used outside of the request/response
// lifecycle, e.g. in a goroutine that outlives the request handler.
//
// Clone must be called before the request handler returns; after that, the
// original context is reset and put back into the pool for reuse by another
// request, racing with the copy.
func (x *Context) Clone() *Context {
clone := *x
// Detach from the request's context, which is canceled once the request finishes.
clone.parentCtx = nil
clone.URLParams.Keys = slices.Clone(x.URLParams.Keys)
clone.URLParams.Values = slices.Clone(x.URLParams.Values)
clone.routeParams.Keys = slices.Clone(x.routeParams.Keys)
clone.routeParams.Values = slices.Clone(x.routeParams.Values)
clone.RoutePatterns = slices.Clone(x.RoutePatterns)
clone.methodsAllowed = slices.Clone(x.methodsAllowed)
return &clone
}
// URLParam returns the corresponding URL parameter value from the request
// routing context.
func (x *Context) URLParam(key string) string {
for k := len(x.URLParams.Keys) - 1; k >= 0; k-- {
if x.URLParams.Keys[k] == key {
return x.URLParams.Values[k]
for i, k := range slices.Backward(x.URLParams.Keys) {
if k == key {
return x.URLParams.Values[i]
}
}
return ""
+100 -33
View File
@@ -5,6 +5,7 @@ import (
"net"
"net/http"
"net/netip"
"slices"
"strings"
)
@@ -38,15 +39,37 @@ const xForwardedForHeader = "X-Forwarded-For"
//
// v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are
// stripped before storage.
func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
//
// Overwriting only protects requests that pass through your proxy. A client
// that reaches this server directly can set the header to anything. Pass
// your proxy's CIDR prefixes as trustedIPPrefixes to close that gap: the
// header is then read only when r.RemoteAddr falls within one of them;
// otherwise r.RemoteAddr itself is the client IP. This mirrors nginx
// (set_real_ip_from), Apache (RemoteIPTrustedProxy), and Caddy
// (trusted_proxies), and Cloudflare's advice to accept origin traffic only
// from its IP ranges. Without trustedIPPrefixes, guarantee at the network
// layer (security group / firewall) that only your proxy can reach this
// server.
//
// r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP",
// "173.245.48.0/20", // Cloudflare IPv4, see https://www.cloudflare.com/ips/
// "2400:cb00::/32", // Cloudflare IPv6
// ))
//
// Panics at startup if any prefix is invalid.
func ClientIPFromHeader(trustedHeader string, trustedIPPrefixes ...string) func(http.Handler) http.Handler {
header := http.CanonicalHeaderKey(trustedHeader)
prefixes := mustParsePrefixes(trustedIPPrefixes)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
values := r.Header.Values(header)
if len(values) > 0 {
if ip, ok := parseHeaderAddr(values[len(values)-1]); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
var found netip.Addr
if peer, untrusted := untrustedPeer(r, prefixes); untrusted {
found = peer
} else if values := r.Header.Values(header); len(values) > 0 {
found, _ = parseHeaderAddr(values[len(values)-1])
}
if found.IsValid() {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found))
}
h.ServeHTTP(w, r)
})
@@ -77,9 +100,15 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// "2600:9000::/28", // CloudFront IPv6
// ))
//
// Calling with no arguments returns the rightmost XFF entry, or no IP if
// that entry doesn't parse (fail-closed) — safe only if you have exactly
// one trusted hop directly in front of this server (e.g., nginx on localhost).
// The TCP peer in r.RemoteAddr is treated as the rightmost hop: if it is
// not within a trusted prefix, it is the client IP and X-Forwarded-For is
// ignored. A client reaching this server directly therefore cannot spoof
// its IP. If r.RemoteAddr doesn't parse, no client IP is set (fail-closed).
//
// At least one prefix is required. For a single trusted hop directly in
// front of this server (e.g., nginx on localhost), pass its address:
//
// r.Use(middleware.ClientIPFromXFF("127.0.0.1/32", "::1/128"))
//
// v4-mapped IPv6 (::ffff:a.b.c.d) folds to plain v4 and IPv6 zones are
// stripped before the prefix check and storage; otherwise an attacker
@@ -88,26 +117,30 @@ func ClientIPFromHeader(trustedHeader string) func(http.Handler) http.Handler {
// If you know the number of trusted proxies but not their IPs, use
// [ClientIPFromXFFTrustedProxies] instead.
//
// Panics at startup if any prefix is invalid.
// Panics at startup if no prefix is given or any prefix is invalid.
func ClientIPFromXFF(trustedIPPrefixes ...string) func(http.Handler) http.Handler {
prefixes := make([]netip.Prefix, len(trustedIPPrefixes))
for i, p := range trustedIPPrefixes {
prefixes[i] = netip.MustParsePrefix(p)
if len(trustedIPPrefixes) == 0 {
panic("middleware.ClientIPFromXFF: at least one trusted IP prefix is required; use ClientIPFromXFFTrustedProxies(1) to trust any peer")
}
prefixes := mustParsePrefixes(trustedIPPrefixes)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var found netip.Addr
walkXFF(r.Header[xForwardedForHeader], func(v string) bool {
ip, ok := parseHeaderAddr(v)
if !ok {
return true // fail-closed; leave found unset
}
if inAnyPrefix(ip, prefixes) {
return false // trusted hop; keep walking left
}
found = ip
return true
})
if peer, untrusted := untrustedPeer(r, prefixes); untrusted {
found = peer
} else {
walkXFF(r.Header[xForwardedForHeader], func(v string) bool {
ip, ok := parseHeaderAddr(v)
if !ok {
return true // fail-closed; leave found unset
}
if inAnyPrefix(ip, prefixes) {
return false // trusted hop; keep walking left
}
found = ip
return true
})
}
if found.IsValid() {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, found))
}
@@ -186,12 +219,8 @@ func ClientIPFromXFFTrustedProxies(numTrustedProxies int) func(http.Handler) htt
// IPv6 zones are preserved (link-local connections may legitimately have one).
func ClientIPFromRemoteAddr(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
host = r.RemoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
}
if ip, err := netip.ParseAddr(host); err == nil {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip.Unmap()))
if ip, ok := parseRemoteAddr(r.RemoteAddr); ok {
r = r.WithContext(context.WithValue(r.Context(), clientIPCtxKey, ip))
}
h.ServeHTTP(w, r)
})
@@ -226,8 +255,7 @@ func GetClientIPAddr(ctx context.Context) netip.Addr {
// comma-separated entries in order received — so an attacker cannot pick
// which value security logic sees by sending a duplicate header.
func walkXFF(headers []string, visit func(entry string) bool) {
for hi := len(headers) - 1; hi >= 0; hi-- {
h := headers[hi]
for _, h := range slices.Backward(headers) {
for h != "" {
var v string
if i := strings.LastIndexByte(h, ','); i >= 0 {
@@ -246,6 +274,45 @@ func walkXFF(headers []string, visit func(entry string) bool) {
}
}
// mustParsePrefixes parses CIDR prefixes, panicking on the first invalid one.
func mustParsePrefixes(cidrs []string) []netip.Prefix {
prefixes := make([]netip.Prefix, len(cidrs))
for i, p := range cidrs {
prefixes[i] = netip.MustParsePrefix(p)
}
return prefixes
}
// untrustedPeer reports whether the TCP peer in r.RemoteAddr is outside
// prefixes. If so, peer is the client IP, or invalid if RemoteAddr doesn't
// parse. With no prefixes, every peer is trusted.
func untrustedPeer(r *http.Request, prefixes []netip.Prefix) (peer netip.Addr, untrusted bool) {
if len(prefixes) == 0 {
return netip.Addr{}, false
}
peer, ok := parseRemoteAddr(r.RemoteAddr)
if !ok {
return netip.Addr{}, true
}
// Zoned addresses never match a prefix, so check a link-local peer without its zone.
return peer, !inAnyPrefix(peer.WithZone(""), prefixes)
}
// parseRemoteAddr parses the host of r.RemoteAddr. v4-mapped IPv6 folds to
// plain v4; the IPv6 zone is preserved (link-local connections may
// legitimately have one).
func parseRemoteAddr(remoteAddr string) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
host = remoteAddr // RemoteAddr may already be a bare IP (e.g. in tests).
}
ip, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
return ip.Unmap(), true
}
// inAnyPrefix reports whether ip falls within any of the given prefixes.
func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
@@ -263,7 +330,7 @@ func inAnyPrefix(ip netip.Addr, prefixes []netip.Prefix) bool {
// address, so without folding/stripping an attacker could escape an
// otherwise valid trust list.
//
// Header-sourced IPs only. [ClientIPFromRemoteAddr] normalizes inline
// Header-sourced IPs only. r.RemoteAddr goes through parseRemoteAddr
// (Unmap, but zone preserved for legitimate link-local connections).
func parseHeaderAddr(s string) (netip.Addr, bool) {
ip, err := netip.ParseAddr(s)
+13 -5
View File
@@ -148,13 +148,21 @@ func NewCompressor(level int, types ...string) *Compressor {
//
// For example, add the Brotli algorithm:
//
// import brotli_enc "gopkg.in/kothar/brotli-go.v0/enc"
// import "github.com/google/brotli/go/cbrotli"
//
// compressor := middleware.NewCompressor(5, "text/html")
// compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
// params := brotli_enc.NewBrotliParams()
// params.SetQuality(level)
// return brotli_enc.NewBrotliWriter(params, w)
// return cbrotli.NewWriter(w, cbrotli.WriterOptions{Quality: level})
// })
//
// Alternatively, this Cgo-free Brotli module can be used:
//
// import "github.com/andybalholm/brotli"
//
// compressor := middleware.NewCompressor(5, "text/html")
//
// compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
// return brotli.NewWriterV2(w, level)
// })
func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc) {
encoding = strings.ToLower(encoding)
@@ -174,7 +182,7 @@ func (c *Compressor) SetEncoder(encoding string, fn EncoderFunc) {
encoder := fn(io.Discard, c.level)
if _, ok := encoder.(ioResetterWriter); ok {
pool := &sync.Pool{
New: func() interface{} {
New: func() any {
return fn(io.Discard, c.level)
},
}
+6
View File
@@ -8,6 +8,7 @@ import (
// ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match.
// An empty charset will allow requests with no Content-Type header or no specified charset.
// Requests without a body (ContentLength == 0) are always allowed.
func ContentCharset(charsets ...string) func(next http.Handler) http.Handler {
for i, c := range charsets {
charsets[i] = strings.ToLower(c)
@@ -15,6 +16,11 @@ func ContentCharset(charsets ...string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength == 0 {
next.ServeHTTP(w, r)
return
}
if !contentEncoding(r.Header.Get("Content-Type"), charsets...) {
w.WriteHeader(http.StatusUnsupportedMediaType)
return
+5 -5
View File
@@ -67,8 +67,8 @@ type LogFormatter interface {
// LogEntry records the final log when a request completes.
// See defaultLogEntry for an example implementation.
type LogEntry interface {
Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{})
Panic(v interface{}, stack []byte)
Write(status, bytes int, header http.Header, elapsed time.Duration, extra any)
Panic(v any, stack []byte)
}
// GetLogEntry returns the in-context LogEntry for a request.
@@ -85,7 +85,7 @@ func WithLogEntry(r *http.Request, entry LogEntry) *http.Request {
// LoggerInterface accepts printing to stdlib logger or compatible logger.
type LoggerInterface interface {
Print(v ...interface{})
Print(v ...any)
}
// DefaultLogFormatter is a simple logger that implements a LogFormatter.
@@ -137,7 +137,7 @@ type defaultLogEntry struct {
useColor bool
}
func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) {
func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra any) {
switch {
case status < 200:
cW(l.buf, l.useColor, bBlue, "%03d", status)
@@ -165,7 +165,7 @@ func (l *defaultLogEntry) Write(status, bytes int, header http.Header, elapsed t
l.Logger.Print(l.buf.String())
}
func (l *defaultLogEntry) Panic(v interface{}, stack []byte) {
func (l *defaultLogEntry) Panic(v any, stack []byte) {
printPrettyStack(v, l.useColor)
}
+3 -3
View File
@@ -51,14 +51,14 @@ func Recoverer(next http.Handler) http.Handler {
// for ability to test the PrintPrettyStack function
var recovererErrorWriter io.Writer = os.Stderr
func PrintPrettyStack(rvr interface{}) {
func PrintPrettyStack(rvr any) {
printPrettyStack(rvr, true)
}
// printPrettyStack prints a formatted stack trace to stderr. When useColor is
// false, ANSI colour codes are suppressed, which is useful for terminals that
// do not support them (e.g. on Windows) or when output is being captured.
func printPrettyStack(rvr interface{}, useColor bool) {
func printPrettyStack(rvr any, useColor bool) {
debugStack := debug.Stack()
s := prettyStack{}
out, err := s.parse(debugStack, rvr, useColor)
@@ -73,7 +73,7 @@ func printPrettyStack(rvr interface{}, useColor bool) {
type prettyStack struct {
}
func (s prettyStack) parse(debugStack []byte, rvr interface{}, useColor bool) ([]byte, error) {
func (s prettyStack) parse(debugStack []byte, rvr any, useColor bool) ([]byte, error) {
var err error
buf := &bytes.Buffer{}
+1 -1
View File
@@ -52,7 +52,7 @@ func init() {
}
// colorWrite
func cW(w io.Writer, useColor bool, color []byte, s string, args ...interface{}) {
func cW(w io.Writer, useColor bool, color []byte, s string, args ...any) {
if IsTTY && useColor {
w.Write(color)
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
)
// WithValue is a middleware that sets a given key/value in a context chain.
func WithValue(key, val interface{}) func(next http.Handler) http.Handler {
func WithValue(key, val any) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), key, val))
+12 -12
View File
@@ -63,6 +63,7 @@ type WrapResponseWriter interface {
Unwrap() http.ResponseWriter
// Discard causes all writes to the original ResponseWriter be discarded,
// instead writing only to the tee'd writer if it's set.
// Flush calls also do not reach the original ResponseWriter.
// The caller is responsible for calling WriteHeader and Write on the
// original ResponseWriter once the processing is done.
Discard()
@@ -119,6 +120,13 @@ func (b *basicWriter) maybeWriteHeader() {
}
}
func (b *basicWriter) flush() {
b.maybeWriteHeader()
if !b.discard {
b.ResponseWriter.(http.Flusher).Flush()
}
}
func (b *basicWriter) Status() int {
return b.code
}
@@ -145,9 +153,7 @@ type flushWriter struct {
}
func (f *flushWriter) Flush() {
f.wroteHeader = true
fl := f.basicWriter.ResponseWriter.(http.Flusher)
fl.Flush()
f.basicWriter.flush()
}
var _ http.Flusher = &flushWriter{}
@@ -170,9 +176,7 @@ type flushHijackWriter struct {
}
func (f *flushHijackWriter) Flush() {
f.wroteHeader = true
fl := f.basicWriter.ResponseWriter.(http.Flusher)
fl.Flush()
f.basicWriter.flush()
}
func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
@@ -192,9 +196,7 @@ type httpFancyWriter struct {
}
func (f *httpFancyWriter) Flush() {
f.wroteHeader = true
fl := f.basicWriter.ResponseWriter.(http.Flusher)
fl.Flush()
f.basicWriter.flush()
}
func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
@@ -237,9 +239,7 @@ type http2FancyWriter struct {
}
func (f *http2FancyWriter) Flush() {
f.wroteHeader = true
fl := f.basicWriter.ResponseWriter.(http.Flusher)
fl.Flush()
f.basicWriter.flush()
}
var _ http.Flusher = &http2FancyWriter{}
+9 -1
View File
@@ -51,7 +51,7 @@ type Mux struct {
// interface.
func NewMux() *Mux {
mux := &Mux{tree: &node{}, pool: &sync.Pool{}}
mux.pool.New = func() interface{} {
mux.pool.New = func() any {
return NewRouteContext()
}
return mux
@@ -305,6 +305,14 @@ func (mx *Mux) Mount(pattern string, handler http.Handler) {
// Assign sub-Router's with the parent not found & method not allowed handler if not specified.
subr, ok := handler.(*Mux)
// Provide runtime safety for ensuring a router isn't mounted onto itself,
// which includes an inline mux derived from it via With()/Group() since
// that shares the same underlying tree. See issue #843.
if ok && subr.tree == mx.tree {
panic(fmt.Sprintf("chi: attempting to Mount() a router onto itself on '%s'", pattern))
}
if ok && subr.notFoundHandler == nil && mx.notFoundHandler != nil {
subr.NotFound(mx.notFoundHandler)
}
+2 -2
View File
@@ -839,8 +839,8 @@ func (ns nodes) Less(i, j int) bool { return ns[i].label < ns[j].label }
// tailSort pushes nodes with '/' as the tail to the end of the list for param nodes.
// The list order determines the traversal order.
func (ns nodes) tailSort() {
for i := len(ns) - 1; i >= 0; i-- {
if ns[i].typ > ntStatic && ns[i].tail == '/' {
for i, n := range slices.Backward(ns) {
if n.typ > ntStatic && n.tail == '/' {
ns.Swap(i, len(ns)-1)
return
}
+2 -2
View File
@@ -468,8 +468,8 @@ github.com/go-acme/lego/v4/challenge
# github.com/go-asn1-ber/asn1-ber v1.5.8
## explicit; go 1.13
github.com/go-asn1-ber/asn1-ber
# github.com/go-chi/chi/v5 v5.3.2
## explicit; go 1.23
# github.com/go-chi/chi/v5 v5.4.0
## explicit; go 1.24
github.com/go-chi/chi/v5
github.com/go-chi/chi/v5/middleware
# github.com/go-chi/httprate v0.16.1