如何在Go中使用http.ResponseWriter来形成一个JSONP响应?

huangapple go评论82阅读模式
英文:

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

huangapple
  • 本文由 发表于 2013年6月11日 12:10:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/17036365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定