Ouput json to http.ResponseWriter with template

前端 未结 1 1375
走了就别回头了
走了就别回头了 2021-01-29 01:16

i\'ve this template:

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

rendered with:



        
相关标签:
1条回答
  • 2021-01-29 01:37

    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"]}
    
    0 讨论(0)
提交回复
热议问题