Merge branch 'get-real-ip'

This commit is contained in:
juancwu 2026-04-26 13:14:40 +00:00
commit d983cca25e
7 changed files with 298 additions and 5 deletions

View file

@ -84,15 +84,23 @@ Middleware values are plain `func(http.Handler) http.Handler`, so any stdlib-com
The `pkg/middleware` package ships:
- **`Logger`** — emits a structured `http.request` record (method, path, status, duration) via [splinter](https://git.juancwu.dev/juancwu/splinter)'s default logger.
- **`Logger`** — emits a structured `http.request` record (method, path, status, duration, client) via [splinter](https://git.juancwu.dev/juancwu/splinter)'s default logger. The `client` field is `r.RemoteAddr`, so pairing with `RealIP` makes it the resolved client IP.
- **`LoggerWith(*splinter.Logger)`** — same, but routes records through the supplied splinter logger instead of the default.
- **`Recoverer`** — catches panics inside handlers, wraps the value with [errx](https://git.juancwu.dev/juancwu/errx) under op `middleware.Recoverer`, logs it with the stack, and writes a 500 response.
- **`RealIP`** — replaces `r.RemoteAddr` with the originating client IP from `CF-Connecting-IP`, `True-Client-IP`, `X-Real-IP`, or `X-Forwarded-For` (in that order). Always trusts these headers — only register it when the service sits behind a trusted proxy.
- **`RealIPWith(trusted ...netip.Prefix)`** — same, but only honors the headers when the immediate peer's IP falls within one of the trusted prefixes. Requests from outside the allowlist pass through untouched.
```go
custom := splinter.New(splinter.WithStream(...))
mux.Use(middleware.Recoverer, middleware.LoggerWith(custom))
```
When using `RealIP` together with `Logger`, register `RealIP` first so the logged `client` field is the resolved client IP rather than the proxy's peer address:
```go
mux.Use(middleware.RealIP, middleware.Logger)
```
## Path parameters
lightmux is a thin wrapper, so path parameters work the stdlib way: