2 回答

TA貢獻1824條經驗 獲得超8個贊
您正在創建一個帶有 nil 正文的新 GET 請求。請參閱 http.NewRequest 的函數簽名
func NewRequest(method, url string, body io.Reader) (*Request, error)
因此,當您訪問 resp.Body 時,它當然會為零。
此外,http.NewRequest 只是返回一個請求,它實際上并沒有執行它。
要使用您的請求實際發出 GET 請求,您需要將其傳遞給 http 客戶端的Do
方法。像這樣:
response, err := http.DefaultClient.Do(resp)
編輯:我還要補充一點,將您的請求命名resp
為令人困惑。我建議將變量重命名為req
或request

TA貢獻2019條經驗 獲得超9個贊
此代碼將解決您的問題。
client := &http.Client{}
apiURL := "https://api.github.com/repos/octocat/Hello-World/pulls/1347"
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
check(err)
}
req.Header.Add("Accept", "application/vnd.github.v3.patch")
response, err := client.Do(req)
if err != nil {
check(err)
}
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
check(err)
}
ctxt.JSON(http.StatusOK, string(contents))
- 2 回答
- 0 關注
- 137 瀏覽
添加回答
舉報