Skip to content

Instantly share code, notes, and snippets.

@yale8848
Created March 29, 2019 02:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yale8848/f9dba9690920871ced844b21d2985278 to your computer and use it in GitHub Desktop.
Save yale8848/f9dba9690920871ced844b21d2985278 to your computer and use it in GitHub Desktop.
Go http request by local port
// Create by Yale 2019/3/29 9:43
package httpclient
import (
"net"
"net/http"
"time"
)
func GetLocalAddrHttpClient(localIp net.IP, localPort int) *http.Client {
addrValue := net.TCPAddr{IP: localIp, Port: localPort}
client := http.Client{}
client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
LocalAddr: &addrValue,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
return &client
}
// Create by Yale 2019/3/29 9:50
package httpclient
import (
"fmt"
"io/ioutil"
"net"
"testing"
)
func TestGetLocalAddrHttpClient(t *testing.T) {
client := GetLocalAddrHttpClient(net.ParseIP("172.16.1.251"), 45678)
r, err := client.Get("https://google.com")
if err != nil {
panic(err)
}
if r.StatusCode == 200 {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
}
@yale8848
Copy link
Author

yale8848 commented Mar 29, 2019

Because use one local port to request data, the second request will faild , so a way to solve this problem is to use one request use one process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment