You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go模板渲染异常:{{.UserData.name}}无法显示用户名

问题排查:Go中objx解析Cookie传递模板不显示用户名

问题说明

使用Go的objx包获取Cookie中的用户名,通过模板传递给HTML页面时,页面{{.UserData.name}}位置无内容显示。已通过日志确认authCookie及用户名已成功获取,但模板渲染未展示预期内容。

相关代码

Callback代码

authCookieValue := objx.New(map[string]interface{}{
            "name": user.Name(),
        }).MustBase64()
        http.SetCookie(w, &http.Cookie{
            Name: "auth",
            Value: authCookieValue,
            Path: "/"})
        log.Printf("user.name",user.Name())
        w.Header()["Location"]=[]string{"/chat"}
        w.WriteHeader(http.StatusTemporaryRedirect)

ServeHTTP代码

func (t *templateHandler)  ServeHTTP(w http.ResponseWriter, r *http.Request){
....
    data := map[string]interface{}{
    "Host": r.Host,
    }
    if authCookie, err := r.Cookie("auth"); err == nil {
        log.Printf("authCookie",authCookie)
        data["UserData"] = objx.MustFromBase64(authCookie.Value)
    }
t.templ.Execute(w,r)
    

HTML模板代码

<form id="chatbox">
    {{.UserData.name}}:<br/>
    <textarea></textarea>
    <input type="submit" value="送信"/>
</form>

日志信息

2023/06/19 09:16:20 authCookie%!(EXTRA *http.Cookie=auth=eyJuYW1lIjoiZ2F0ZSBnYXRlIn0=)
2023/06/19 09:16:26 user.name%!(EXTRA string=gate gate)
2023/06/19 09:16:26 authCookie%!(EXTRA *http.Cookie=auth=eyJuYW1lIjoiZ2F0ZSBnYXRlIn0=)

问题原因及解决

问题出在ServeHTTP方法的模板执行步骤:
原本代码执行模板时传递的参数是请求对象r,但我们构建的包含UserData的上下文是data变量,模板无法从请求对象中读取UserData。

需将代码修改为:

t.templ.Execute(w, data)

这样模板才能获取到包含UserData的上下文数据,正确渲染出用户名。

内容的提问来源于stack exchange,提问作者gate gate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:35:18