I am trying to convert HTTP JSON body response to map[string]interface{}
in Go.
This is the code I wrote:
func fromHTTPResponse(httpResponse *http.Response, errMsg string )(APIResponse, error){
temp, _ := strconv.Atoi(httpResponse.Status)
var data map[string]interface{}
resp, errResp := json.Marshal(httpResponse.Body)
defer httpResponse.Body.Close()
if errResp != nil {
return APIResponse{}, errResp
}
err := json.Unmarshal(resp, &data)
if err != nil {
return APIResponse{}, err
}
return APIResponse{httpResponse.Status, data, (temp == OK_RESPONE_CODE), errMsg, map[string]interface{}{} }, nil
}
I successfully connect to the server. The response's body contains JSON data. After running the code, data points to nil
, why is that?
http.Response.Body
is io.ReadCloser
. So use this:
err := json.NewDecoder(httpResponse.Body).Decode(&data)
The *http.Response.Body
is of type io.ReadCloser
. And you are not using right method to read the body data and to convert it into []byte
. Try to use this:
resp, errResp := ioutil.ReadAll(httpResponse.Body)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With