实现 `Consent-Middleware` 读取 `CookieConsent=granted`
解读
- CookieConsent 场景:国内《个人信息保护法》要求明示同意后才能采集用户数据,前端通过 CookieConsent=granted 标记用户已点击“同意”。
- 中间件定位:该中间件属于横切鉴权层,需无侵入地嵌入 Negroni 链,不能修改业务 Handler。
- 性能要求:Negroni 常用于高并发网关,必须避免正则和反射,仅用标准库
http.Request.Cookie。 - 错误处理:禁止 panic,需显式终止后续中间件,Negroni 惯例是不调用 next() 即可短路。
- 测试友好:中间件应可配置 Cookie 名称与期望值,方便单元测试 mock。
知识点
- Negroni 中间件签名:
func(http.ResponseWriter, *http.Request, http.HandlerFunc) - Cookie 读取:
req.Cookie(name)返回*http.Cookie, error,区分大小写。 - 短路机制:不执行 next() 即终止链,需提前写入状态码与响应头。
- 并发安全:禁止在闭包中修改外部变量,所有状态通过参数传递。
- 国内合规:403 比 401 更合适,因 401 触发浏览器弹窗,不符合国内产品体验。
答案
package consent
import (
"net/http"
)
// ConsentMiddleware 返回一个 Negroni 兼容的中间件
func ConsentMiddleware(cookieName, expectValue string) func(http.ResponseWriter, *http.Request, http.HandlerFunc) {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
c, err := r.Cookie(cookieName)
if err != nil || c.Value != expectValue {
// 显式指定 UTF-8,避免中文乱码
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("用户未同意 Cookie 政策"))
return
}
next(w, r)
}
}
使用示例:
n := negroni.New()
n.Use(negroni.HandlerFunc(ConsentMiddleware("CookieConsent", "granted")))
n.UseHandler(router)
http.ListenAndServe(":8080", n)
拓展思考
-
性能优化:
- 预编译字符串比较:若 Cookie 值固定,可在初始化阶段缓存 expectValue,避免每次请求比较。
- 布隆过滤器:当多值白名单场景下,用位数组降低内存占用。
-
合规增强:
- 双层校验:前端 JS 写入 Cookie 后,后端再次通过短信验证码确认,满足《个人信息保护法》第 29 条“单独同意”要求。
- 日志留痕:记录用户 ID、时间戳、IP,保存 3 年以上,应对网信办抽查。
-
可观测性:
- Prometheus 埋点:拒绝次数与拒绝原因分别打标,区分“无 Cookie”与“值错误”,方便运营漏斗分析。
-
灰度发布:
- 配置中心热更新:通过 Apollo/Nacos 动态切换强制校验/仅日志记录,零重启回滚。