I need to make a GET request to an API with a bearer token in the authorization request. How can I do this in Go? I have the following code, but I haven\'t had success.
For control over HTTP client headers, redirect policy, and other settings, create a Client:
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
// Create a Bearer string by appending string access token
var bearer = "Bearer " +
// Create a new request using http
req, err := http.NewRequest("GET", url, nil)
// add authorization header to the req
req.Header.Add("Authorization", bearer)
// Send req using http Client
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println("Error on response.\n[ERRO] -", err)
}
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string([]byte(body)))
}
The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.
A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.
For more information on Client and Transport check golang spec for net/http package