Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTTP JSON body response to map in Go

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?

like image 507
DarkSkylo Avatar asked Nov 26 '18 18:11

DarkSkylo


2 Answers

http.Response.Body is io.ReadCloser. So use this:

err := json.NewDecoder(httpResponse.Body).Decode(&data)
like image 143
nightfury1204 Avatar answered Sep 21 '22 20:09

nightfury1204


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)
like image 44
Shudipta Sharma Avatar answered Sep 19 '22 20:09

Shudipta Sharma