douchuntang2827 2016-03-28 07:02
浏览 85
已采纳

在Golang中使用ioutil进行读取时,向HTTP响应JSON正文添加了无效的null

So this one is driving me insane. I'm not even sure if the title is 100% correct because I'm having some trouble to narrow the issue down to one specific part.

I have two applications that talk to each other via REST. One accepts the HTTP GET request from the other app, and answers with some JSON. For the HTTP router I use Gorilla/mux btw. So far so good.

My first application (let's call it FooReader), is calling my second application (let's call it FooWriter) via HTTP GET:

req, err := http.NewRequest("GET", url, nil)
req.Header.Set("uuid", "my uuid")
req.Header.Set("api_token", "my token")
req.Header.Set("Content-Type", "application/json")

client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
    ...
}
defer resp.Body.Close()

This works just fine. As you can see I'm sending some additional stuff in the header, that's why I'm not using http.Get(). (Is there a better way to do this?)

Now FooWriter receives that request and processes it:

...
var successJSON = "{\"foo\":\"bar\"}"
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.Write([]byte(successJSON))
w.WriteHeader(200)

if err := json.NewEncoder(w).Encode(err); err != nil {
    ...
}

Back in FooReader I now receive the response from FooWriter and read it (I've added the Do() call again for clarity):

resp, err := client.Do(req)
if err != nil {
    ...
}
defer resp.Body.Close()

fmt.Println("response Code:", resp.StatusCode)

body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1048576))
if err != nil {
    ...
}

fmt.Println("response Body:", string(body))

Now comes the weird part: When I print the response body like I do in the last line, there is an additional null added to the original JSON string:

response Code: 200
response Body: {"foo":"bar"}null

My guess is that there is some nil thrown in there before the JSON decoding, but I just can't find it. Also I'm guessing that the issue has to be on the FooReader side, because I'm using the exact same code on FooWriter side on some other part of the application, which works fine.

Did I miss anything? Any help is much appreciated!

  • 写回答

1条回答 默认 最新

  • doushai4890 2016-03-28 07:57
    关注

    if err := json.NewEncoder(w).Encode(err) is printing null when err is nil. Pass response to encode and make err part of it so only one json structure is printed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置