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

GoHTML模板无法获取字段数据问题求助

问题原因与解决方案

问题出在Go结构体的字段可见性上:html/template模板引擎只能访问导出的结构体字段(即字段名首字母大写),你定义的结构体字段hostName、hostPronouns都是小写开头,属于非导出字段,模板无法直接读取它们的值。而使用{{.}}能看到数据是因为结构体的默认字符串格式化会输出所有字段,但模板不能单独访问非导出字段。

修改后的Go代码

func processor(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Redirect(w, r, "/", http.StatusSeeOther)
        return
    }

    userName := r.FormValue("user")
    userPronouns := r.FormValue("pronouns")

    d := struct {
        HostName     string // 首字母大写,转为导出字段
        HostPronouns string
    }{
        HostName:     userName,
        HostPronouns: userPronouns,
    }

    tpl.ExecuteTemplate(w, "processor.gohtml", d)

    fmt.Println(d.HostName)
    fmt.Println(d.HostPronouns)
}

修改后的HTML模板代码

<body>
    <h1>BALLS</h1>
    <h2> {{.HostName}} </h2>
    <h3> {{.HostPronouns}} </h3> <!-- 可选:添加代词字段展示 -->
</body>

修改后模板就能正确读取并显示结构体中的字段值了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:09:25