Ouput json to http.ResponseWriter with template

不问归期 提交于 2019-12-20 05:47:08

问题


i've this template:

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

rendered with:

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

if i send it to a http.ResponseWriter the output text is escaped.

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

how can i write a json this way?


回答1:


You shouldn't use Go's template engine (neither text/template nor html/template) to generate JSON output, as the template engine has no knowledge of JSON syntax and rules (escaping).

Instead use the 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.

Example:

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)
}

Outputs (try it on the Go Playground):

{"resources":["r1","r2"]}


来源:https://stackoverflow.com/questions/55021403/ouput-json-to-http-responsewriter-with-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!