Get Golang to accept a token for GET authorization

I cant seem to get my script to accept my bearer token. Here is my script:

func main(){

    url := "https://www.mywebsite.com"
    response, err := http.Get(url)   
    if err != nil {
        log.Fatalln(err)
        fmt.Print(err.Error())
        os.Exit(1)
    }

    response.Header.Add("Authorization", os.ExpandEnv("$BEARER_TOKEN"))

    fmt.Println(response.Header.Get("authorization"))


    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Println(string(responseData))
}

I did fmt.Println(response.Header.Get("authorization")) to see if it was accepting the token and it printed the token correctly, so im not sure why its not accepting it for the GET request.

Ive also tried response.Header.Set instead of response.Header.Add and it had the same outcome.

The response I get back when I run that script is: {"code":16,"message":"token not valid for running mode"} but I know the token is correct because I tried it in a curl command and I got the output that I wanted


Solution 1:

try to use http.NewRequest() and set request Header Authorization

package main

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

func main() {

    url := "https://www.mywebsite.com"

    client := http.Client{Timeout: 5 * time.Second}
    request, err := http.NewRequest(http.MethodGet, url, nil)

    request.Header.Set("Authorization", os.ExpandEnv("$BEARER_TOKEN"))
    request.Header.Set("Content-Type", "application/json") // => your content-type

    response, err := client.Do(request)
    if err != nil {
        panic(err)
    }

    responseData, err := ioutil.ReadAll(response.Body)
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Println(string(responseData))
}