This question already has an answer here:
I'd like to save a JSON response to a text file before parsing it:
req, err := http.NewRequest("POST", url, body)
req.Header.Set("Authorization", "secret_key")
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
f, err := os.Create("./response.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
io.Copy(f, resp.Body)
var result JSONResult
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Fatal(err)
}
It successfully writes the JSON to a file but then fails on the decoding step with an error that just says EOF
. If I parse before writing to file it parses ok, but then the file is empty. Can someone please explain what's happening here? Thanks!
</div>
http.Response.Body
is of type io.ReadCloser
, which can only be read once (as you can see it does not have a method to rewind).
So alternatively for decoding purposes you could read your just created file.
Or if the response is not large (or you could trim it with io.LimitReader
) - you can read it into a buffer
(not tested, something along these lines):
f, err := os.Create("./response.json")
if err != nil {
log.Fatal(err)
}
defer f.Close()
var buf bytes.Buffer
tee := io.TeeReader(r.Body, &buf)
io.Copy(f, tee)
var result JSONResult
if err := json.NewDecoder(buf).Decode(&result); err != nil {
log.Fatal(err)
}
References: