亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 golang 中的 get 請求獲取狀態碼

從 golang 中的 get 請求獲取狀態碼

Go
慕田峪7331174 2022-12-19 21:17:41
我正在嘗試在 goland 中獲取 http 狀態代碼。我也在傳遞授權令牌。到目前為止,這是我嘗試過的:func StatusCode(PAGE string, AUTH string) (r string){    resp, err := http.NewRequest("GET", PAGE, nil)    if err != nil {        log.Fatal(err)    }    resp.Header.Set("Authorization", AUTH)    fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))    r := resp.StatusCode + http.StatusText(resp.StatusCode)}基本上我想得到這個:r = "200 OK"orr= "400 Bad request"以前的代碼是從resp.StatusCode和http.StatusText(resp.StatusCode)抱怨的
查看完整描述

1 回答

?
牧羊人nacy

TA貢獻1862條經驗 獲得超7個贊

有兩個問題。第一個是應用程序使用請求作為響應。 執行請求以獲得響應。

第二個問題是resp.StatusCode + http.StatusText(resp.StatusCode)編譯不通過,因為操作數類型不匹配。該值resp.StatusCode是一個int. 的值為http.StatusText(resp.StatusCode)string。Go 沒有將數字隱式轉換為字符串的功能,這會使它按照您期望的方式工作。

r := resp.Status如果您想要從服務器發送的狀態字符串,請使用。

用于r := fmt.Sprintf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode))從服務器的狀態代碼和 Go 的狀態字符串構造狀態字符串。

這是代碼:

func StatusCode(PAGE string, AUTH string) (r string) {

    // Setup the request.

    req, err := http.NewRequest("GET", PAGE, nil)

    if err != nil {

        log.Fatal(err)

    }

    req.Header.Set("Authorization", AUTH)


    // Execute the request.

    resp, err := http.DefaultClient.Do(req)

    if err != nil {

        return err.Error()

    }

    

    // Close response body as required.

    defer resp.Body.Close()


    fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))


    return resp.Status

    // or fmt.Sprintf("%d %s", resp.StatusCode, http.StatusText(resp.StatusCode))

}


查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 274 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號