问题
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:
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))
来源:https://stackoverflow.com/questions/17036365/how-should-a-jsonp-response-be-formed-in-go-using-http-responsewriter