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

为什么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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?