Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang force http request to specific ip (similar to curl --resolve)

How can I force a golang https get request to use a specific IP address. I want to skip DNS resolution and provide the IP myself. The equivalent in curl would be a --resolve as illustrated below.

curl https://domain.com/dir/filename --resolve "domain.com:443:10.10.10.10"

Since this is ssl I want to avoid substituting in the IP for the domain as in the following example.

curl https://10.10.10.10/dir/filename --header "Host: domain.com"

like image 965
Ryan D. Avatar asked Nov 16 '16 04:11

Ryan D.


2 Answers

You can provide a custom Transport.DialContext function.

func main() {
    dialer := &net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        // DualStack: true, // this is deprecated as of go 1.16
    }
    // or create your own transport, there's an example on godoc.
    http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
        if addr == "google.com:443" {
            addr = "216.58.198.206:443"
        }
        return dialer.DialContext(ctx, network, addr)
    }
    resp, err := http.Get("https://google.com")
    log.Println(resp.Header, err)
}
like image 85
OneOfOne Avatar answered Sep 20 '22 09:09

OneOfOne


OneOfOne's answer above is excellent. I am posting the full working package code here to make it easier for noobs like me. I added a couple of println so that you could see the addr value before and after modification.

package main

import (
    "context"
    "fmt"
    "log"
    "net"
    "net/http"
    "time"
)

func main() {
    dialer := &net.Dialer{
        Timeout:   30 * time.Second,
        KeepAlive: 30 * time.Second,
        DualStack: true,
    }
    // or create your own transport, there's an example on godoc.
    http.DefaultTransport.(*http.Transport).DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
        fmt.Println("address original =", addr)
        if addr == "google.com:443" {
            addr = "216.58.198.206:443"
            fmt.Println("address modified =", addr)
        }
        return dialer.DialContext(ctx, network, addr)
    }
    resp, err := http.Get("https://google.com")
    log.Println(resp.Header, err)
}
like image 45
Ryan D. Avatar answered Sep 18 '22 09:09

Ryan D.