如何在Go中为HTTP GET请求设置headers?
大家好!我刚开始学习Go,在处理HTTP请求时遇到了问题。我需要向一个外部API发送GET请求,该API需要特定的headers进行身份验证。例如,我想传递"Authorization: Bearer my-token"和"Accept: application/json" headers。
我尝试这样做:
```go
resp, err := http.Get("https://api.example.com/data")
```
但这不允许添加headers。后来我在文档中发现应该使用http.NewRequest,但我无法正确设置headers。我的代码如下:
```go
req, err := http.NewRequest("GET", "https://api.example.com/data", nil)
req.Header.Set("Authorization", "Bearer my-token")
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
```
但我不确定这是否正确。此外,我想了解如何处理错误,以及如果需要设置多个headers该怎么办。也许有更好的方法?