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 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误