How to bind an http.Client in Go to an IP Address

后端 未结 2 1946
南旧
南旧 2020-12-15 14:37

I have a client machine with multiple NICs, how do I bind an http.Client in Go to a certain NIC or to a certain SRC IP Address?

Say you have some very basic http cli

2条回答
  •  失恋的感觉
    2020-12-15 15:16

    Here is a fully working example that incorporates the answer from Tim. I also broke out all of the nested pieces to make it easier to read and learn from.

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "net"
        "net/http"
        "time"
    )
    
    func main() {
        localAddr, err := net.ResolveIPAddr("ip", "10.128.64.219")
        if err != nil {
            panic(err)
        }
    
        localTCPAddr := net.TCPAddr{
            IP: localAddr.IP,
        }
    
        d := net.Dialer{
            LocalAddr: &localTCPAddr,
            Timeout:   30 * time.Second,
            KeepAlive: 30 * time.Second,
        }
    
        tr := &http.Transport{
            Proxy:               http.ProxyFromEnvironment,
            Dial:                d.Dial,
            TLSHandshakeTimeout: 10 * time.Second,
        }
    
        webclient := &http.Client{Transport: tr}
    
        // Use NewRequest so we can change the UserAgent string in the header
        req, err := http.NewRequest("GET", "http://www.google.com:80", nil)
        if err != nil {
            panic(err)
        }
    
        res, err := webclient.Do(req)
        if err != nil {
            panic(err)
        }
    
        fmt.Println("DEBUG", res)
        defer res.Body.Close()
    
        content, err := ioutil.ReadAll(res.Body)
        if err != nil {
            panic(err)
        }
        fmt.Printf("%s", string(content))
    }
    

提交回复
热议问题