为什么http.Request.URL.Host的地址对于2个不同的http.Request结构是一样的?

时间:2017-06-01 13:12:21

标签: pointers go struct

此代码是一个来自大型代码库的自包含示例,用于尝试复制错误。运行此程序时,&request.URL.Host&request1.URL.Host的地址相同。为什么?根据我的理解,这些是两种不同的结构,因此URL.Host不应该具有相同的地址。

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)
}

1 个答案:

答案 0 :(得分:1)

http.Request是一个结构,其URL字段是指针

URL *url.URL

在您的代码中,您有一个uri变量,其中包含*url.URL类型的指针。

然后创建2个请求,将指针存储在request1request2变量中,但是您指定了相同的值,指向其URL字段的指针。

因此,只有一个url.URL值,您可以将其地址分配给request1.URLrequest2.URL。然后打印request1.URL.Hostrequest2.URL.Host的地址,但由于request1.URLrequest2.URL都指向相同且唯一的url.URL(struct)值,因此地址该结构的Host字段将是相同的。 2个请求结构没有明确的url.URL值。

相关问题