shadyabhi
shadyabhi

Reputation: 17234

Why is the address of http.Request.URL.Host same for 2 different http.Request structures?

This code is a self-contained example from a large code base to try to replicate a bug. When this program is run, the address of both &request.URL.Host and &request1.URL.Host is same. Why? From my understanding, these are 2 different structures so URL.Host should not have the same address.

package main

import (
        "crypto/tls"
        "fmt"
        "net/http"
        "net/url"
)

func main() {
        hostname := "www.google.com"
        uri, err := url.Parse("http://www.google.com/")
        if err != nil {
                panic(err)
        }
        var tlsConfig *tls.Config
        tlsConfig = &tls.Config{
                ServerName:         hostname,
                InsecureSkipVerify: true,
        }

        client := &http.Client{
                Transport: &http.Transport{
                        DisableKeepAlives: true,
                        TLSClientConfig:   tlsConfig,
                },
        }
        request1 := &http.Request{
                Header: http.Header{"User-Agent": {"Foo"}},
                Host:   hostname,
                Method: "GET",
                URL:    uri,
        }
        request2 := &http.Request{
                Header: http.Header{"User-Agent": {"Foo"}},
                Host:   hostname,
                Method: "GET",
                URL:    uri,
        }

        fmt.Printf("Address1: %s, Address2: %s\n", &request1.URL.Host, &request2.URL.Host)
        resp, err := client.Do(request1)
        if err != nil {
                panic(err)
        }
        defer resp.Body.Close()
        fmt.Printf("\nResponse: %s", resp)
}

Upvotes: 0

Views: 149

Answers (1)

icza
icza

Reputation: 417622

http.Request is a struct, whose URL field is a pointer:

URL *url.URL

In your code you have a single uri variable holding a pointer of type *url.URL.

Then you create 2 requests, storing the pointers in request1 and request2 variables, but you assign the same value, the same pointer to their URL field.

So there is a single url.URL value, and you assign its address to both request1.URL and request2.URL. Then you print the addresses of request1.URL.Host and request2.URL.Host, but since both request1.URL and request2.URL point to the same and only url.URL (struct) value, the address of the Host field of that struct will be the same. There are no distinct url.URL values for the 2 request structs.

Upvotes: 1

Related Questions