http – How can I make a request with a bearer token in Go-ThrowExceptions

Exception or error:

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.\n[ERRO] -", err)
    }

    body, _ := ioutil.ReadAll(resp.Body)
    log.Println(string([]byte(body)))
}
How to solve:

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[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

Answer:

I had to add a client.CheckRedirect Function(seen below) in order to pass the Bearer token to the API.

bearer := "Bearer " + token

    req, err := http.NewRequest("GET", url, bytes.NewBuffer(nil))
    req.Header.Set("Authorization", bearer)
    req.Header.Add("Accept", "application/json")

    client := &http.Client{}


    client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
        for key, val := range via[0].Header {
            req.Header[key] = val
        }
        return err
    }
    resp, err := client.Do(req)
    if err != nil {
        log.Println("Error on response.\n[ERRO] -", err)
    } else {
        defer resp.Body.Close()
        data, _ := ioutil.ReadAll(resp.Body)
        fmt.Println(string(data))
    }
}

Answer:

I made a super-little-basic library for execute basic request like:

package main
import (
     request "github.com/alessiosavi/Requests"
)

func main(){
    // Create a key-value list of headers
    headers := request.CreateHeaderList(`Accept`, `application/json`, "Authorization", "Bearer "+auth.IAMToken)
    resp :=request.SendRequest(`http://your_site.com`, `GET`, headers, nil))
}

Here you can find the request implementation:
https://github.com/alessiosavi/Requests/blob/e7ca66bde738b6224fba2b6f146a8dbee67d3323/Requests.go

Here you can find how i use the library for Bearer Auth and other auth type:
https://github.com/alessiosavi/GoCloudant/blob/a8ad3a7990f04ea728bb327d6faea6af3e5455ca/cloudant.go

Leave a Reply

Your email address will not be published. Required fields are marked *