从 golang 中的 get 请求获取状态码

我正在尝试在 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"

or

r= "400 Bad request"

以前的代码是从resp.StatusCode和http.StatusText(resp.StatusCode)抱怨的


慕田峪7331174
浏览 274回答 1
1回答

牧羊人nacy

有两个问题。第一个是应用程序使用请求作为响应。 执行请求以获得响应。第二个问题是resp.StatusCode + http.StatusText(resp.StatusCode)编译不通过,因为操作数类型不匹配。该值resp.StatusCode是一个int. 的值为http.StatusText(resp.StatusCode)a 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))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go