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

标签 http dictionary go httpresponse

我正在尝试将 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.Bodyio.ReadCloser。所以使用这个:

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

关于http - 将 HTTP JSON 正文响应转换为 Go 中的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53486878/

相关文章:

http - 具有多个值的golang http解析 header

java - 如何进行服务器端 HTTP 重定向而不是元刷新

python - 查找仅在第一个字典中出现的键值对

google-app-engine - 'goapp deploy' 和 'appcf.py' 在 Google App Engine 上部署我的应用程序之间的区别?

Java 小服务程序 : Differentiate between GET and POST

python - 用数字表示按键排序字典

c# - 将 Dictionary<int, Enumerable> 转换为 Dictionary<int, Enumerable> 反转内容

go - 在 golang 中处理逻辑错误与编程错误的惯用方法

http - 在不进行大量分配的情况下在 io.ReadCloser 中查找字符串

xml - 没有来自 XMLHttpRequest 的响应