Golang Http請求返回結(jié)果處理
更新時間:2022年08月08日 11:43:37 作者:lovenliu
本文主要介紹了Golang Http請求返回結(jié)果處理,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
在 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) }
到此這篇關(guān)于Golang Http請求返回結(jié)果處理的文章就介紹到這了,更多相關(guān)Golang Http請求返回結(jié)果內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!