使用模板将json输出到http.ResponseWriter

问题描述 投票:0回答:1

我有这个模板:

var ListTemplate = `
{
    "resources": [
        {{ StringsJoin . ", " }}
    ]
  }
`

渲染:

JoinFunc := template.FuncMap{"StringsJoin": strings.Join}
tmpl := template.Must(template.New("").Funcs(JoinFunc).Parse(ListTemplate))

如果我将它发送到http.ResponseWriter,输出文本将被转义。

var list []string
tmpl.Execute(w, list)

我怎么能用这种方式写一个json?

json http go go-templates
1个回答
4
投票

您不应该使用Go的模板引擎(text/templatehtml/template)来生成JSON输出,因为模板引擎不了解JSON语法和规则(转义)。

而是使用encoding/json包生成JSON。您可以使用json.Encoder直接将响应写入/流式传输到io.Writer,例如http.ResponseWriter

例:

type Output struct {
    Resources []string `json:"resources"`
}

obj := Output{
    Resources: []string{"r1", "r2"},
}

enc := json.NewEncoder(w)

if err := enc.Encode(obj); err != nil {
    // Handle error
    fmt.Println(err)
}

输出(在Go Playground上试试):

{"resources":["r1","r2"]}
© www.soinside.com 2019 - 2024. All rights reserved.