Golang传递数据有效载荷给HTTP客户端

huangapple go评论90阅读模式
英文:

golang passing data payload from HTTP client

问题

我有一个HTTPS端点,使用以下cURL命令可以正常工作:

curl -k -u xyz:pqr \
  --data "grant_type=client_credentials" \
  https://my-url

现在我正在尝试使用golang以类似的方式调用相同的API端点:

data := url.Values{}
data.Set("grant_type", "client_credentials")
req, err := http.NewRequestWithContext(
  ctx,
  "POST",
  "https://my-url",
  strings.NewReader(data.Encode())
)

它失败并返回以下错误信息:

{
   "error_description":"grant_type is required",
   "error":"invalid_request"
}

我已经将grant_type作为http.NewRequestWithContext()函数的最后一个参数传递了。我漏掉了什么?

英文:

I have an HTTPS endpoint that works fine with a cURL command like this:

curl -k -u xyz:pqr \
  --data "grant_type=client_credentials" \
  https://my-url

Now I am trying to use golang to call the same API endpoint like this:

data := url.Values{}
data.Set("grant_type", "client_credentials")
req, err := http.NewRequestWithContext(
  ctx,
  "POST",
  "https://my-url",
  strings.NewReader(data.Encode())
)

It fails with the error body:

  {
     "error_description":"grant_type is required",
      "error":"invalid_request"
  }

I am already passing grant_type as the last argument to the http.NewRequestWithContext() function.

What am I missing?

答案1

得分: 1

你没有正确翻译curl命令。这个工具可能会有帮助:https://mholt.github.io/curl-to-go/

基本上,你需要添加用户认证。

req.SetBasicAuth("xyz", "pqr")
// 可能还需要设置`Content-Type`
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

-k在curl中似乎也会从文件中读取一些curl参数。你需要确保将它们正确翻译过来。根据你的示例,我无法看到它们是什么。

英文:

You are not translating the curl correctly. This tool might be helpful: https://mholt.github.io/curl-to-go/

Essentially you need to add user auth.

req.SetBasicAuth("xyz", "pqr")
// Might help to set the `Content-Type` too
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

-k on curl seems to be reading some curl arguments from a file too. You are going to want to make sure you translate those over as well. I cannot see what they are from your example.

huangapple
  • 本文由 发表于 2022年5月20日 03:22:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/72310055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定