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:
51
middleware/recovery_test.go
Normal file
51
middleware/recovery_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.codelab.vc/pkg/httpx/middleware"
|
||||
)
|
||||
|
||||
func TestRecovery(t *testing.T) {
|
||||
t.Run("recovers from panic and returns error", func(t *testing.T) {
|
||||
base := mockTransport(func(req *http.Request) (*http.Response, error) {
|
||||
panic("something went wrong")
|
||||
})
|
||||
|
||||
transport := middleware.Recovery()(base)
|
||||
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
|
||||
|
||||
resp, err := transport.RoundTrip(req)
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
if resp != nil {
|
||||
t.Errorf("expected nil response, got %v", resp)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "panic recovered") {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), "panic recovered")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "something went wrong") {
|
||||
t.Errorf("error = %q, want it to contain %q", err.Error(), "something went wrong")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("passes through normal responses", func(t *testing.T) {
|
||||
base := mockTransport(func(req *http.Request) (*http.Response, error) {
|
||||
return okResponse(), nil
|
||||
})
|
||||
|
||||
transport := middleware.Recovery()(base)
|
||||
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
|
||||
|
||||
resp, err := transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Errorf("got status %d, want %d", resp.StatusCode, http.StatusOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user