英文:
Golang Make GET Request With Data
问题
可以尝试使用以下代码在Golang中进行GET请求,并传递数据:
import (
"net/http"
"net/url"
)
func main() {
params := url.Values{}
params.Add("api_key", "myapikey")
req, err := http.NewRequest("GET", "https://someendpoint", nil)
if err != nil {
// 处理错误
}
req.URL.RawQuery = params.Encode()
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
// 处理错误
}
defer resp.Body.Close()
// 处理响应
}
这样,你可以将数据作为查询参数添加到URL中,并发送GET请求。
英文:
Is it possible to do a GET request with data such as:
curl -G -v https://someendpoint \
-d "api_key=myapikey"
Which works. In Golang I tried:
payload := url.Values{}
payload.Add("api_key", "myapikey")
req, err := http.NewRequest(
"GET",
"https://someendpoint",
bytes.NewBufferString(payload.Encode()),
)
But the api key is not being recognised.
答案1
得分: 6
curl命令通过URL查询字符串将API密钥传递给服务器。以下是在Go中执行相同操作的方法:
payload := url.Values{}
payload.Add("api_key", "myapikey")
req, err := http.NewRequest("GET", "https://someendpoint?"+payload.Encode(), nil)
这段代码将API密钥添加到payload
中,并使用payload.Encode()
将其编码为URL查询字符串。然后,使用http.NewRequest
创建一个GET请求,并将URL设置为"https://someendpoint?" + payload.Encode()
。
英文:
The curl command passes the API key to the server in the URL query string. Here's how to do the same in Go:
payload := url.Values{}
payload.Add("api_key", "myapikey")
req, err := http.NewRequest("GET", "https://someendpoint?" + payload.Encode(), nil)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论