在 Go 中 Http 请求的返回结果为 *http.Response 类型,Response.Body 类型为 io.Reader,把请求结果转化为Map需要进行一些处理。来源地址:https://www.yii666.com/blog/298244.html文章来源地址:https://www.yii666.com/blog/298244.html

写一个公共方法来进行Response转Map处理:文章来源地址https://www.yii666.com/blog/298244.html地址:https://www.yii666.com/blog/298244.html

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
}

然后就可以在请求后使用:文章地址https://www.yii666.com/blog/298244.html

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