登录
首页 >  Golang >  Go问答

Go 代码调用 API 时遇到 401 错误,但 cURL 正常运行

来源:stackoverflow

时间:2024-03-26 14:03:30 128浏览 收藏

在使用 Go 代码调用 API 时,开发人员遇到了 401 错误,而使用 cURL 却能正常运行。经检查,发现 Go 代码中使用的 API 主机名不正确,导致身份验证失败。通过修正主机名,Go 代码成功获取了预期的响应,而 cURL 也继续正常运行。

问题内容

我编写了一个简单的 go 代码,它将 get 请求发送到 api,并作为响应收到 401 错误。但是,当我使用 curl 时,我收到了所需的响应。我还使用 api tester 得到了预期的响应。因此,我相信我的代码一定有问题,但我无法找出问题所在。

下面是我的 go 代码,响应 401 错误

func main() {
    clusterid := os.getenv("cluster_id")
    apiurl := "https://api.qubole.com/api/v1.3/clusters/"+clusterid+"/state"
    auth_token := os.getenv("x_auth_token")
    fmt.println("url - ",apiurl)
    req, err := http.newrequest("get", apiurl, nil)
    if(err != nil){
        fmt.println("error in getting rest response",err)
    }
    req.header.set("x-auth-token", auth_token)
    req.header.set("content-type", "application/json")
    req.header.set("accept", "application/json")

    res, err := http.defaultclient.do(req)
    if(err != nil){
       fmt.println("error: no response received", err)
    }
    defer res.body.close()
    //print raw response body for debugging purposes
    body, _ := ioutil.readall(res.body)
    fmt.println(string(body))
}

我得到的响应/错误摘录如下:

url -  https://api.qubole.com/api/v1.3/clusters/presto-bi/state
{"error":{"error_code":401,"error_message":"invalid token"}}

现在,以下是 curl 命令,它返回我所需的响应

curl -X GET -H "X-AUTH-TOKEN:$X_AUTH_TOKEN" -H "Content-Type: application/json" -H "Accept: application/json" "https://us.qubole.com/api/v1.3/clusters/presto-bi/state"

下面是我收到的标准输出,符合预期:{"state":"down"}%


解决方案


需要再次检查 golang 处的 api 主机名并再次进行curl。谢谢!

该错误是因为 api 提供商的文档指出主机错误 (API Documentation) 。但是,由于门户登录名是 us.qubole.com (PORTAL Login URL),因此编写 curl 命令时就考虑到了这一点。

我只是在这里猜测,没有足够的信息。我假设 clusterid := os.getenv("cluster_id")presto-bi。如果是这种情况,那么您只是在路径中缺少“集群”。

apiUrl := "https://api.qubole.com/api/v1.3/clusters/"+clusterId+"/state"

另外,您不应该使用 us.qubole.com/api 而不是 api.qubole.com 吗?

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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