英文:
How should a JSONP response be formed in Go using http.ResponseWriter?
问题
我正在开发一个接受JSONP请求的Go API。我可以将一个结构体序列化为JSON并返回,但是将JSON包装在填充中或回调函数中有点麻烦,因为Write()
的参数需要是一个字节切片:
callback := req.FormValue("callback")
// ...
jsonBytes, _ := json.Marshal(resp)
if callback != "" {
jsonStr := callback + "(" + string(jsonBytes) + ")"
jsonBytes = []byte(jsonStr)
}
responseWriter.Write(jsonBytes)
我想我会将这个封装在一个函数中。大部分时候,我觉得字符串/[]byte的转换有点奇怪。有没有更好的方法来做到这一点?
英文:
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?
答案1
得分: 5
使用fmt.Fprintf
来简化代码:
if callback != "" {
fmt.Fprintf(w, "%s(%s)", callback, jsonBytes)
} else {
w.Write(jsonBytes)
}
或者如果你只想在一个地方写入:
jsonBytes = []byte(fmt.Sprintf("%s(%s)", callback, jsonBytes))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论