日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

Golang?Http請求返回結(jié)果處理_Golang

作者:lovenliu ? 更新時間: 2022-10-03 編程語言

在 Go 中 Http 請求的返回結(jié)果為 *http.Response 類型,Response.Body 類型為 io.Reader,把請求結(jié)果轉(zhuǎn)化為Map需要進行一些處理。

寫一個公共方法來進行Response轉(zhuǎn)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)
}

原文鏈接:https://blog.csdn.net/lypeng_/article/details/102741359

欄目分類
最近更新