Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set headers in http get request?

Tags:

http

go

People also ask

Can we send headers in GET request?

For example, to send a GET request with a custom header name, you can use the "X-Real-IP" header, which defines the client's IP address. For a load balancer service, "client" is the last remote host. Your load balancer intercepts traffic between the client and your server.

Can HTTP GET have headers?

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back. They're optional though.

How do I set up HTTP headers?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.


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", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

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": []string{"www.host.com"},
    "Content-Type": []string{"application/json"},
    "Authorization": []string{"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")
}