如何使用http.ResponseWriter在Go中形成JSONP响应?

问题描述:

I'm developing an API that accepts JSONP requests in Go. I can serialize a struct into JSON and return it, but wrapping the JSON in padding, or the callback function, is a little awkward, since the argument to Write() needs to be a byte slice:

callback := req.FormValue("callback")

// ...

jsonBytes, _ := json.Marshal(resp)
if callback != "" {
    jsonStr := callback + "(" + string(jsonBytes) + ")"
    jsonBytes = []byte(jsonStr)
}
responseWriter.Write(jsonBytes)

I suppose I will encapsulate this in some function. Mostly I find the string/[]byte conversion funky. Is there a better way to do this?

我正在开发一个可以在Go中接受JSONP请求的API。 我可以将结构序列化为JSON并将其返回,但是将JSON包装在padding或回调函数中有点尴尬,因为 Write() code>的参数需要为字节切片:

 回调:= req.FormValue(“ callback”)
 
 // ... 
 
jsonBytes,_:= json.Marshal(resp)
if回调 !=“” {
 jsonStr:=回调+“(” +字符串(jsonBytes)+“)” 
 jsonBytes = [] byte(jsonStr)
} 
responseWriter.Write(jsonBytes)
  code>   pre> 
 
 

我想我会将其封装在某些函数中。 通常,我发现字符串/ [] byte转换很时髦。 有更好的方法吗? p> div>

Use fmt.Fprintf to simplify it:

if callback != "" {
    fmt.Fprintf(w, "%s(%s)", callback, jsonBytes)
} else {
    w.Write(jsonBytes)
}

Or if you only want to write in one place:

jsonBytes = []byte(fmt.Sprintf("%s(%s)", callback, jsonBytes))