直接用c.Cookie("theme")读、c.SetCookie()写,需联动前端CSS变量,Cookie为唯一权威源,SameSite=Lax且生产环境Secure=true+HTTPS。

直接用 c.Cookie("theme") 读、c.SetCookie() 写就行,但必须和前端 CSS 变量联动,且注意 Cookie 生命周期与主题持久化逻辑的一致性。
Cookie 读写必须走 Echo 封装接口,不能手动 set-header
Echo 禁用手动调用 http.SetCookie 或直接操作 ResponseWriter.Header()。否则会和框架内部 Header 写入冲突,导致 Cookie 丢失或被浏览器忽略。
- 读取:用
c.Cookie("theme"),返回*http.Cookie和error;若不存在会返回http.ErrNoCookie,别用c.Request().Cookie("theme") - 写入:先构造
http.Cookie实例,再传给c.SetCookie();MaxAge和Expires二选一即可,同时设可能被浏览器忽略 - 示例写入(7 天有效期):
cookie := &http.Cookie{ Name: "theme", Value: "dark", Path: "/", MaxAge: 60 * 60 * 24 * 7, HttpOnly: false, Secure: false, // 开发环境可设 false;生产务必为 true + HTTPS SameSite: http.SameSiteLaxMode, } c.SetCookie(cookie)
前端如何同步应用 Cookie 中的主题值
Cookie 只是存储介质,真正生效靠前端把值注入 CSS 变量。Echo 不处理这部分,得自己在 HTML 模板或 JS 中读取并设置。
- 服务端渲染时(如使用
c.Render),可在模板里内联 JS:<script> const theme = document.cookie.replace(/(?:(?:^|.*;\s*)theme\s*\=\s*([^;]*).*$)|^.*$/, "$1"); if (theme) document.documentElement.setAttribute('data-theme', theme); </script> - 纯前端 SPA 场景:用
document.cookie解析后,调用document.documentElement.style.setProperty('--primary', ...)动态更新变量 - 注意:CSS 变量名(如
--background)必须和 Echo Editor 那套主题数据结构对齐,否则改了 Cookie 也没视觉变化
Cookie 与 localStorage 协同问题容易被忽略
用户在页面点切换主题时,往往既写 Cookie 又写 localStorage。但两者不同步会导致“刷新后回退到旧主题”或“跨标签不一致”。
- 推荐策略:以 Cookie 为唯一权威源,前端初始化时只读 Cookie,不读
localStorage - 如果必须双写(比如要支持离线主题预览),需监听
storage事件做反向同步:window.addEventListener('storage', (e) => { if (e.key === 'theme') document.cookie = `theme=${e.newValue}; path=/; max-age=604800`; }); - 域名和路径配置必须匹配:确保
SetCookie的Domain和Path能被所有前端路由访问到,否则子路径下读不到
最常漏掉的是 Cookie 的 SameSite 和 Secure 配置——开发时设 false 很方便,但上线后若没配 Secure: true + HTTPS,Chrome 会静默丢弃 Cookie;SameSite=Lax 是当前兼容性与安全性平衡的合理选择。











