一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Golang Http请求返回结果处理代码示例

时间:2022-08-08 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Golang Http请求返回结果处理代码示例,对大家的学习有一定的帮助,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

在 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)
}

热门栏目