doucuo8618 2017-06-01 13:12
浏览 86
已采纳

为什么2个不同的http.Request结构的http.Request.URL.Host地址相同?

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
", &request1.URL.Host, &request2.URL.Host)
        resp, err := client.Do(request1)
        if err != nil {
                panic(err)
        }
        defer resp.Body.Close()
        fmt.Printf("
Response: %s", resp)
}
  • 写回答

1条回答 默认 最新

  • dropbox1111 2017-06-01 13:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题