- ResponseCache: Redis-backed HTTP response caching for public GET endpoints with configurable TTLs per endpoint prefix (tracks 15m, search 5m, etc.) - CacheHeaders: CDN-optimized Cache-Control headers per asset type (static 1yr immutable, audio 7d, HLS 60s, images 30d, API no-cache) - Integrated both middlewares into the router middleware stack - Unit tests for cache key generation, header rules, and config Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"testing"
|
|
)
|
|
|
|
func TestGenerateCacheKey(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
prefix string
|
|
uri string
|
|
}{
|
|
{"simple path", "http_cache", "/api/v1/tracks"},
|
|
{"path with query", "http_cache", "/api/v1/tracks?page=1&limit=20"},
|
|
{"search query", "http_cache", "/api/v1/search?q=test&type=track"},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
key := generateCacheKey(tt.prefix, tt.uri)
|
|
if key == "" {
|
|
t.Error("expected non-empty cache key")
|
|
}
|
|
if len(key) < 10 {
|
|
t.Errorf("cache key too short: %s", key)
|
|
}
|
|
|
|
// Same input should produce same key
|
|
key2 := generateCacheKey(tt.prefix, tt.uri)
|
|
if key != key2 {
|
|
t.Errorf("cache key not deterministic: %s != %s", key, key2)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Different URIs should produce different keys
|
|
key1 := generateCacheKey("http_cache", "/api/v1/tracks?page=1")
|
|
key2 := generateCacheKey("http_cache", "/api/v1/tracks?page=2")
|
|
if key1 == key2 {
|
|
t.Error("different URIs should produce different cache keys")
|
|
}
|
|
}
|
|
|
|
func TestCacheResponseWriter(t *testing.T) {
|
|
// Test that cachedResponse struct can be marshaled
|
|
resp := cachedResponse{
|
|
Status: 200,
|
|
ContentType: "application/json",
|
|
Body: `{"data":[]}`,
|
|
Headers: map[string]string{"Content-Type": "application/json"},
|
|
}
|
|
|
|
if resp.Status != 200 {
|
|
t.Errorf("expected status 200, got %d", resp.Status)
|
|
}
|
|
if resp.ContentType != "application/json" {
|
|
t.Errorf("expected application/json, got %s", resp.ContentType)
|
|
}
|
|
}
|