How to set headers in http get request?

I'm doing a simple http GET in Go:

client := &http.Client{} req, _ := http.NewRequest("GET", url, nil) res, _ := client.Do(req) 

But I can't found a way to customize the request header in the doc, thanks

0

4 Answers

The Header field of the Request is public. You may do this :

req.Header.Set("name", "value") 

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "", nil) if err != nil { ... } req.Host = "domain.tld" client := &http.Client{} resp, err := client.Do(req) 
1

If you want to set more than one header, this can be handy rather than writing set statements.

client := http.Client{} req , err := http.NewRequest("GET", url, nil) if err != nil { //Handle Error } req.Header = http.Header{ "Host": {""}, "Content-Type": {"application/json"}, "Authorization": {"Bearer Token"}, } res , err := client.Do(req) if err != nil { //Handle Error } 

Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

func yourHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("header_name", "header_value") } 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like