Golang Http请求返回结果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Golang Http请求返回结果

lovenliu   2022-09-28 我要评论

在 Go 中 Http 请求的返回结果为 *http.Response 类型,Response.Body 类型为 io.Reader,把请求结果转化为Map需要进行一些处理。

写一个公共方法来进行Response转Map处理:

package util

import (
    "encoding/json"
    "net/http"
    "io/ioutil"
)

func ParseResponse(response *http.Response) (map[string]interface{}, error){
    var result map[string]interface{}
    body,err := ioutil.ReadAll(response.Body)
    if err == nil {
        err = json.Unmarshal(body, &result)
    }

    return result,err
}

然后就可以在请求后使用:

req := http.NewRequest("GET", "http://test.com", nil)
req.Header.Set("Content-type", "application/json")
client := &http.Client{}
response,err := client.Do(req)

if err == nil {
    // 解析Response
    returnMap,err := util.ParseResponse(response)
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们