Files
fanqie-go/internal/handlers/gzip.go
T
chenxin 1a4997e031 ✨ feat(api): 统一响应格式并完善参数体系与文档
- 正文参数支持语义值(plain/html/keep/remove)与别名(img_mode/review_mode),URL 参数优先于配置
- 修复纯文本被段评强制包回 HTML、HTML 模式段评注入失效的问题
- 修复 PKCS7 填充弱校验导致漫画/正文偶发解密乱码返回 200 的问题
- 搜索结果展平:去 search_tabs 层与 selected_tab_idx/server_ab_params,提升 has_more/next_offset
- 全接口解包字符串形式的 JSON 字段(category_schema 等),缓存出口幂等处理
- 序列化关闭 HTML 转义,video/audio 播放链接可直接复制播放
- video 响应透传 CENC 加密状态(key_seed/kid/encryption_method)
- 新增 gzip 中间件,JSON/文本响应压缩约 81%,二进制透传
- 漫画默认输出模式改为 proxy(url 模式链接 404 且内容加密不可用)
- openapi.yaml:补全 23 个路径参数定义、tab_type 完整枚举、CDN 签名说明,示例更新
2026-10-09 21:01:18 +08:00

75 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package handlers
import (
"compress/gzip"
"net/http"
"strings"
)
// Gzip 对 JSON/文本响应启用 gzip 压缩(仅客户端声明 Accept-Encoding: gzip 时)。
// 图片/音频等二进制响应不在白名单内,原样透传。
func Gzip(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
gw := &gzipWriter{ResponseWriter: w}
defer gw.close()
next.ServeHTTP(gw, r)
})
}
type gzipWriter struct {
http.ResponseWriter
zw *gzip.Writer
decided bool // 是否已根据 Content-Type 做过压缩决定
headerSent bool
}
func (g *gzipWriter) WriteHeader(status int) {
if g.headerSent {
return
}
if !g.decided {
g.decide()
}
g.ResponseWriter.WriteHeader(status)
g.headerSent = true
}
func (g *gzipWriter) Write(b []byte) (int, error) {
if !g.headerSent {
// handler 未显式 WriteHeader(fmt.Fprint 直接写)时的隐式 200
if !g.decided {
g.decide()
}
g.ResponseWriter.WriteHeader(http.StatusOK)
g.headerSent = true
}
if g.zw != nil {
return g.zw.Write(b)
}
return g.ResponseWriter.Write(b)
}
// decide 在首个响应头确定时判断是否压缩(此时 handler 已设置 Content-Type)
func (g *gzipWriter) decide() {
g.decided = true
ct := g.Header().Get("Content-Type")
for _, prefix := range []string{"application/json", "text/html", "text/plain"} {
if strings.HasPrefix(ct, prefix) {
g.Header().Set("Content-Encoding", "gzip")
g.Header().Del("Content-Length")
g.zw = gzip.NewWriter(g.ResponseWriter)
return
}
}
}
func (g *gzipWriter) close() {
if g.zw != nil {
g.zw.Close()
}
}