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:
2026-03-20 14:22:14 +03:00
parent 8d322123a4
commit a90c4cd7fa
9 changed files with 608 additions and 0 deletions

View 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)
}
})
}