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.

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

报告相同问题?

悬赏问题

  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊