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.
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
resp, err := http.Get(url)
resp.Header.Add("Bearer", "token")
if err != nil {
log.Println("Erro ao realizar request.
[ERRO] -", err)
}
body, _ := ioutil.ReadAll(resp.Body)
log.Println(string([]byte(body)))
}
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 " + <ACCESS TOKEN HERE>
// 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.
[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
The application adds the token to the response returned from the server. To fix, add the token to the request sent to the server.
The http.Get
function used in the question is a helper function that creates and executes the request with the default HTTP client. To set the request header, the application must write code for these individual steps. Here's the code:
func main() {
url := "https://api.globalcode.com.br/v1/publico/eventos"
// Create request object.
req, err := http.NewRequest("GET", url, nil)
// Set the header in the request.
req.Header.Set("Bearer", "token")
// Execute the request.
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal("Erro ao realizar request.
[ERRO] -", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
os.Stdout.Write(body)
}