- 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
52 lines
1.4 KiB
Go
52 lines
1.4 KiB
Go
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)
|
|
}
|
|
})
|
|
}
|