Golang Make GET Request With Data

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

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)

huangapple
  • 本文由 发表于 2015年12月28日 14:29:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/34488687.html
匿名

发表评论

匿名网友

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

确定