英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论