Skip to content

Instantly share code, notes, and snippets.

@2minchul
Created April 16, 2019 05:55
Show Gist options
  • Save 2minchul/191716b3ca8799f53362746731d08e91 to your computer and use it in GitHub Desktop.
Save 2minchul/191716b3ca8799f53362746731d08e91 to your computer and use it in GitHub Desktop.
golang http client using specific network adapter
package main
import (
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
)
func PanicErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
// Select network adapter that using 192.168.0.50
// and it will be connect to port 0 (dynamically generate an unused port number)
addr, err := net.ResolveTCPAddr("tcp", "192.168.0.50:0")
PanicErr(err)
dialer := &net.Dialer{LocalAddr: addr}
dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := dialer.Dial(network, addr)
return conn, err
}
transport := &http.Transport{DialContext: dialContext}
client := &http.Client{
Transport: transport,
}
// http request
response, err := client.Get("https://api.ipify.org/") // get my IP address
PanicErr(err)
data, err := ioutil.ReadAll(response.Body);
PanicErr(err)
fmt.Println(string(data))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment