-2

I'm creating a reverse proxy in Golang and I'm having trouble trying to grab online examples on how to add HTTP headers to an API call.

Here is my API call:

package handlers

import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)


func (s *Server) getApiCall(w http.ResponseWriter, r *http.Request) {
    resp, err := http.Get("https://url.com")
    if err != nil {
        log.Fatalln(err)
    }
    //We Read the response body on the line below.
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Fatalln(err)
    }
    //Convert the body to type string
    sb := string(body)
    log.Printf(sb)
    fmt.Fprintf(w, sb)
}

Where in my function can I add an Authorization header with the a Bearer <TOKEN> as its value?

I'm new with Go, to my understanding this should be enough code, but if you need more detail about my backend just add a comment in what needs clarification.

andres
  • 1,558
  • 7
  • 24
  • 62
  • 3
    [Read the opening summary of `net/http`](https://pkg.go.dev/net/http#pkg-overview), there's a complete example that starts off with "For control over HTTP client headers, redirect policy, and other settings" – Adrian Jan 31 '22 at 18:37

1 Answers1

2

You can't use http.Get, instead use http.NewRequest to create a request object then add the headers to it.

One example:

client := &http.Client{}

req, err := http.NewRequest("GET", "https://url.com", nil)
if err != nil {
    // handle error
}

req.Header.Add("Authorization", "Bearer ...")
resp, err := client.Do(req)
if err != nil {
    // handle error
}

For more details take a look at http package doc.

novalagung
  • 10,905
  • 4
  • 58
  • 82