Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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))) } 
like image 531
Matheus Alcântara Avatar asked Jul 21 '18 01:07

Matheus Alcântara


People also ask

How do I send a Bearer Token in request?

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

What can you do with a Bearer Token?

You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for.


2 Answers

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

like image 179
Himanshu Avatar answered Oct 11 '22 11:10

Himanshu


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

like image 20
alessiosavi Avatar answered Oct 11 '22 10:10

alessiosavi