How to set which IP to use for a HTTP request?

前端 未结 1 635
南方客
南方客 2020-12-06 07:09

I dont know if it\'s possible as the std lib does not state anything about the current address being used:

http://golang.org/pkg/net/http/

resp, err          


        
相关标签:
1条回答
  • 2020-12-06 07:29

    You can set a custom Dialer in the Client's Transport.

    // Create a transport like http.DefaultTransport, but with a specified localAddr
    transport := &http.Transport{
        Proxy: http.ProxyFromEnvironment,
        DialContext: (&net.Dialer{
            Timeout:   30 * time.Second,
            KeepAlive: 30 * time.Second,
            LocalAddr: localAddr,
            DualStack: true,
        }).DialContext,
        MaxIdleConns:          100,
        IdleConnTimeout:       90 * time.Second,
        TLSHandshakeTimeout:   10 * time.Second,
        ExpectContinueTimeout: 1 * time.Second,
    }
    
    client := &http.Client{
        Transport: transport,
    }
    
    0 讨论(0)
提交回复
热议问题