此代码是一个来自大型代码库的自包含示例,用于尝试复制错误。运行此程序时,&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)
}
答案 0 :(得分:1)
http.Request
是一个结构,其URL
字段是指针:
URL *url.URL
在您的代码中,您有一个uri
变量,其中包含*url.URL
类型的指针。
然后创建2个请求,将指针存储在request1
和request2
变量中,但是您指定了相同的值,指向其URL
字段的指针。
因此,只有一个url.URL
值,您可以将其地址分配给request1.URL
和request2.URL
。然后打印request1.URL.Host
和request2.URL.Host
的地址,但由于request1.URL
和request2.URL
都指向相同且唯一的url.URL
(struct)值,因此地址该结构的Host
字段将是相同的。 2个请求结构没有明确的url.URL
值。