提供 `/-/consent` 接口供前端获取当前同意状态

解读

在国内合规场景下,前端往往需要在首屏就判断用户是否已同意《隐私政策》《用户协议》,从而决定是否弹出“授权弹窗”。/-/consent 是一个只读健康型接口,职责单一:返回当前会话(或设备)的同意状态,不修改任何数据,因此必须:

  1. 支持跨域安全调用(CORS)
  2. 返回标准化 JSON,方便前端直接消费
  3. 与 Negroni 的洋葱链无缝集成,不侵入业务 Handler
  4. 考虑缓存与并发,避免每次请求都穿透到数据库

知识点

  • Negroni 中间件签名:func(http.ResponseWriter, *http.Request, http.HandlerFunc)
  • 路由注册:Negroni 本身不带路由,需配合 net/http.ServeMux 或第三方路由(如 httprouter、chi)
  • 跨域处理:通过 n.Use(cors.New(...)) 插入 CORS 中间件
  • 状态存储:内存 map(单机)、Redis(集群)、加密 Cookie(无状态)三种主流方案
  • 缓存策略:对只读接口可设置 Cache-Control: private, max-age=5 降低重复请求
  • 错误包装:统一返回 {"code":0,"msg":"ok","data":{...}},非 200 场景也走 JSON,方便前端拦截器处理

答案

package main

import (
	"encoding/json"
	"net/http"
	"sync"
	"time"

	"github.com/urfave/negroni/v3"
)

// 1. 同意状态存储:单机内存版,生产可替换为 Redis
type consentRepo struct {
	m  map[string]bool // key=sessionID
	mu sync.RWMutex
}

func (r *consentRepo) Get(sessionID string) bool {
	r.mu.RLock()
	defer r.mu.RUnlock()
	return r.m[sessionID]
}

var repo = &consentRepo{m: make(map[string]bool)}

// 2. 只读接口 Handler
func consentHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		writeJSON(w, http.StatusMethodNotAllowed, map[string]any{"code": -1, "msg": "method not allowed"})
		return
	}
	sessionID := r.Header.Get("X-Session-ID")
	if sessionID == "" {
		// 允许前端未登录时调用,返回 false 即可
		sessionID = "anonymous"
	}
	agreed := repo.Get(sessionID)
	writeJSON(w, http.StatusOK, map[string]any{"code": 0, "data": map[string]bool{"consented": agreed}})
}

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "private, max-age=5")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

// 3. CORS 中间件(简单版)
func cors() negroni.Handler {
	return negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Headers", "X-Session-ID, Content-Type")
		if r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next(w, r)
	})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/-/consent", consentHandler)

	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewLogger())
	n.Use(cors())
	n.UseHandler(mux)

	srv := &http.Server{
		Addr:         ":8080",
		Handler:      n,
		ReadTimeout:  3 * time.Second,
		WriteTimeout: 3 * time.Second,
	}
	_ = srv.ListenAndServe()
}

关键点

  • 使用 negroni.HandlerFunc 快速插入 CORS,保持与标准库兼容
  • 接口路径固定为 /-/consent,符合国内“健康检查”命名惯例
  • 返回结构统一,前端可直接 res.data.consented 取值
  • 缓存头 max-age=5 降低并发,兼顾实时性与性能

拓展思考

  1. 无状态方案:把同意状态写入加密 Cookie(如 Consent=1; HttpOnly; SameSite=Lax),接口直接读 Cookie,彻底去掉后端存储,适合高并发、无登录场景
  2. 集群同步:若采用 Redis,可封装 consentRepo 为接口,底层切换 Redis/Hazelcast,零改动业务代码
  3. 埋点与审计:在 Negroni 链中再插一个 AuditMiddleware,记录每次 /-/consent 调用的会话 ID、IP、耗时,方便合规审计
  4. 灰度策略:结合配置中心,动态返回不同版本的同意文案链接,实现灰度发布
  5. 安全加固:对敏感业务可增加二次签名(如 X-Session-Sign=hmac(sessionID+timestamp)),防止前端伪造会话