登录
首页 >  Golang >  Go问答

在golang中使用get请求获取状态码

来源:stackoverflow

时间:2024-02-06 18:00:23 478浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《在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.statuscodehttp.statustext(resp.statuscode)


正确答案


有两个问题。第一个是应用程序使用请求作为响应。 Execute the request 获取回复。

第二个问题是 resp.statuscode + http.statustext(resp.statuscode) 无法编译,因为操作数类型不匹配。值 resp.StatusCodeinthttp.StatusText(resp.StatusCode) 的值是 string。 go 没有将数字隐式转换为字符串的功能,因此无法按照您期望的方式工作。

如果您想要 status string as sent from the server,请使用 r := resp.status

使用 r := fmt.sprintf("%d %s", resp.statuscode, http.statustext(resp.statuscode)) 从服务器的状态代码和 go 的状态字符串构造一个状态字符串。 p>

代码如下:

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))
}

以上就是《在golang中使用get请求获取状态码》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>