在 Go 中 Http 请求的返回结果为 *http.Response 类型,Response.Body 类型为 io.Reader,把请求结果转化为Map需要进行一些处理。
写一个公共方法来进行Response转Map处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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 } |
然后就可以在请求后使用:
1
2
3
4
5
6
7
8
9
|
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请求返回结果内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/lypeng_/article/details/102741359