在 Go 中 Http 请求的返回结果为 *http.Response 类型,Response.Body 类型为 io.Reader,把请求结果转化为Map需要进行一些处理。 写一个
在 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)
}
到此这篇关于golang Http请求返回结果处理的文章就介绍到这了,更多相关Golang Http请求返回结果内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: GolangHttp请求返回结果处理
本文链接: https://www.lsjlt.com/news/120978.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0