如何使用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?

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))