Created
March 29, 2019 02:32
-
-
Save yale8848/f9dba9690920871ced844b21d2985278 to your computer and use it in GitHub Desktop.
Go http request by local port
This file contains hidden or 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
// 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 | |
} |
This file contains hidden or 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
// 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)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.