How to set headers in an HTTP GET request in Go?
Hello colleagues! I've just started learning Go and encountered a problem when working with HTTP requests. I need to send a GET request to an external API that requires specific headers for authentication. For example, I want to pass the "Authorization: Bearer my-token" and "Accept: application/json" headers.
I tried doing this:
```go
resp, err := http.Get("https://api.example.com/data")
```
But this doesn't allow adding headers. Then I found in the documentation that I need to use http.NewRequest, but I can't figure out how to properly set the headers. My code looks like this:
```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{}
No answers yet.
Log in to leave an answer
Blogs