将 HTTP JSON 正文响应转换为 Go 中的映射

Convert HTTP JSON body response to map in Go

我正在尝试将 HTTP JSON 正文响应转换为 Go 中的 map[string]interface{}

这是我写的代码:

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
}

我成功连接到服务器。响应正文包含 JSON 数据。 运行代码后,数据指向nil,这是为什么呢?

*http.Response.Body 的类型是 io.ReadCloser。而且您没有使用正确的方法来读取正文数据并将其转换为 []byte。尝试使用这个:

resp, errResp := ioutil.ReadAll(httpResponse.Body)

http.Response.Bodyio.ReadCloser。所以使用这个:

err := json.NewDecoder(httpResponse.Body).Decode(&data)