[英]401 Error when consuming an API from Go Code, while cURL Works well
I've written a simple go code that, sends a GET request to an API and in response I receive a 401 error. 我编写了一个简单的go代码,该代码将GET请求发送到API,并且作为响应,我收到401错误。 However when I use cURL, I receive the desired response.
但是,当我使用cURL时,会收到所需的响应。 I also get expected response using API Tester .
我还可以使用API Tester获得预期的响应。 So, I believe, there has to be something wrong with my code and that, I'm unable to find out.
因此,我相信我的代码一定有问题,而我无法发现。
Below is my Go code, that, responds with 401 Error 以下是我的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))
}
Extract of Response/Error I get, is as follows: 我得到的响应/错误摘录如下:
URL - https://api.qubole.com/api/v1.3/clusters/presto-bi/state
{"error":{"error_code":401,"error_message":"Invalid Token"}}
Now, Following is the cURL command that, returns me the desired response 现在,下面是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"
below is the stdout I receive, which is as expected: {"state":"DOWN"}%
以下是我收到的标准输出,符合预期:
{"state":"DOWN"}%
I'm just guessing here without enough information. 我只是在猜测没有足够的信息。 I'm assuming
clusterId := os.Getenv("CLUSTER_ID")
is presto-bi
. 我假设
clusterId := os.Getenv("CLUSTER_ID")
是presto-bi
。 If that is the case, then you are just missing "clusters" in your path. 如果是这种情况,那么您只是在路径中缺少“集群”。
apiUrl := "https://api.qubole.com/api/v1.3/clusters/"+clusterId+"/state"
Also, shouldn't you use us.qubole.com/api
instead of api.qubole.com
? 另外,您不应该使用
us.qubole.com/api
而不是api.qubole.com
吗?
Need check api hostname at golang and curl again. 需要在golang上检查api主机名,然后再次卷曲。 Thanks!
谢谢!
The error is because, the documentation of API provider states the host WRONG ( API Documentation ) . 该错误是因为,API提供程序的文档说明了主机WRONG( API文档 )。 But, since the portal login is us.qubole.com ( PORTAL Login URL ), cURL command was written considering that in mind.
但是,由于门户网站登录名是us.qubole.com( 门户登录名URL ),因此在编写cURL命令时考虑了这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.