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?