Adding basic authentication to http get

I am having trouble adding basic authentication to my http get. Curl commands seem to work fine against this. But I get a 403 forbidden when I try the call from my golang script. Any help will be appreciated, thank you.

func main() {
	var url = "http://localhost:4002/wallet/address"

	req, err := http.Get(url)
	if err != nil {
		panic(err)
	}

	req.Header.Add("Authorization", "Basic dGVzdHVzZXI6dGVzdHVzZXI=")

	defer req.Body.Close()

	fmt.Println(req)
}

I was able to get this to work. The issue was I needed to create a client object to set the header. Here is the working code.

var url = "http://localhost:4002/wallet/address"

	req, _ := http.NewRequest("GET", url, nil)

	req.Header.Set("Authorization", "Basic dGVzdHVzZXI6dGVzdHVzZXI=")

	client := &http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
	}

	defer resp.Body.Close()
	data, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(data))
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.