在cURL运作良好的情况下,从Go代码使用API​​时出现401错误

时间:2018-11-18 14:58:30

标签: rest api http 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"}%

2 个答案:

答案 0 :(得分:1)

我只是在这里猜测没有足够的信息。我假设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吗?

答案 1 :(得分:1)

需要在golang上检查api主机名,然后再次卷曲。谢谢!

错误是因为,API提供程序的文档说明了主机WRONG(API Documentation)。但是,由于门户网站登录名为us.qubole.com(PORTAL Login URL),因此考虑到了这一点而编写了cURL命令。