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:
33
middleware/auth.go
Normal file
33
middleware/auth.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// BearerAuth returns a middleware that sets the Authorization header to a
|
||||
// Bearer token obtained by calling tokenFunc on each request. If tokenFunc
|
||||
// returns an error, the request is not sent and the error is returned.
|
||||
func BearerAuth(tokenFunc func(ctx context.Context) (string, error)) Middleware {
|
||||
return func(next http.RoundTripper) http.RoundTripper {
|
||||
return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
token, err := tokenFunc(req.Context())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
return next.RoundTrip(req)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// BasicAuth returns a middleware that sets HTTP Basic Authentication
|
||||
// credentials on every outgoing request.
|
||||
func BasicAuth(username, password string) Middleware {
|
||||
return func(next http.RoundTripper) http.RoundTripper {
|
||||
return RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
req.SetBasicAuth(username, password)
|
||||
return next.RoundTrip(req)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user