refactor(internal/handler): optimize image request handling based on Accept header

This commit is contained in:
wood chen 2024-11-17 09:38:01 +08:00
parent e4d7a16f99
commit c71698e5ad

View File

@ -112,22 +112,18 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 特别处理图片请求 // 特别处理图片请求
if utils.IsImageRequest(r.URL.Path) { if utils.IsImageRequest(r.URL.Path) {
// 设置优化的 Accept 头 // 获取 Accept 头
accept := r.Header.Get("Accept") accept := r.Header.Get("Accept")
if accept != "" {
proxyReq.Header.Set("Accept", accept) // 根据 Accept 头设置合适的图片格式
} else { if strings.Contains(accept, "image/avif") {
proxyReq.Header.Set("Accept", "image/avif,image/webp,image/jpeg,image/png,*/*;q=0.8") proxyReq.Header.Set("Accept", "image/avif")
} else if strings.Contains(accept, "image/webp") {
proxyReq.Header.Set("Accept", "image/webp")
} }
// 设置 Cloudflare 特定的头部 // 设置 Cloudflare 特定的头部
proxyReq.Header.Set("CF-Accept-Content", "image/avif,image/webp") proxyReq.Header.Set("CF-Image-Format", "auto") // 让 Cloudflare 根据 Accept 头自动选择格式
proxyReq.Header.Set("CF-Optimize-Images", "on")
// 删除可能影响缓存的头部
proxyReq.Header.Del("If-None-Match")
proxyReq.Header.Del("If-Modified-Since")
proxyReq.Header.Set("Cache-Control", "no-cache")
} }
// 设置其他必要的头部 // 设置其他必要的头部