du512926 2018-11-18 14:58
浏览 139
已采纳

当cURL正常工作时,从Go代码中使用API​​时出现401错误

I've written a simple go code that, sends a GET request to an API and in response I receive a 401 error. However when I use cURL, I receive the desired response. I also get expected response using 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

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 -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"}%

  • 写回答

2条回答 默认 最新

  • duanlang0025 2018-11-18 15:35
    关注

    Need check api hostname at golang and curl again. Thanks!

    The error is because, the documentation of API provider states the host WRONG (API Documentation) . But, since the portal login is us.qubole.com (PORTAL Login URL), cURL command was written considering that in mind.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?