How should a JSONP response be formed in Go using http.ResponseWriter?

主宰稳场 提交于 2019-12-23 19:36:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!