在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!
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.