使用模板输出 json 到 http.ResponseWriter

Ouput json to http.ResponseWriter with template

我有这个模板:

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?

你不应该使用 Go 的模板引擎(text/template nor html/template)来生成 JSON 输出,因为模板引擎不知道 JSON 语法和规则(转义)。

改为使用 encoding/json package to generate JSON. You may use json.Encoder to write / stream the response directly to an io.Writer, such as 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"]}