Created
April 16, 2019 05:55
-
-
Save 2minchul/191716b3ca8799f53362746731d08e91 to your computer and use it in GitHub Desktop.
golang http client using specific network adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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