Add standard middlewares: logging, headers, auth, and panic recovery
- Logging: structured slog output with method, URL, status, duration - DefaultHeaders/UserAgent: inject headers without overwriting existing - BearerAuth/BasicAuth: per-request token resolution and static credentials - Recovery: catches panics in the RoundTripper chain
This commit is contained in:
29
middleware/headers.go
Normal file
29
middleware/headers.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// DefaultHeaders returns a middleware that adds the given headers to every
|
||||
// outgoing request. Existing headers on the request are not overwritten.
|
||||
func DefaultHeaders(headers http.Header) Middleware {
|
||||
return func(next http.RoundTripper) http.RoundTripper {
|
||||
return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
for key, values := range headers {
|
||||
if req.Header.Get(key) != "" {
|
||||
continue
|
||||
}
|
||||
for _, v := range values {
|
||||
req.Header.Add(key, v)
|
||||
}
|
||||
}
|
||||
return next.RoundTrip(req)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// UserAgent returns a middleware that sets the User-Agent header on every
|
||||
// outgoing request, unless one is already present.
|
||||
func UserAgent(ua string) Middleware {
|
||||
return DefaultHeaders(http.Header{
|
||||
"User-Agent": {ua},
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user