How can I make a request with a bearer token in Go

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.\n[ERROR] -", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Println("Error while reading the response bytes:", err)
    }
    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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)