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

当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条)

报告相同问题?

悬赏问题

  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形