2022-07-05 22:54:43

golang httpclient

http客户端请求绑定指定源IP

package main import ( "fmt" "io/ioutil" "net" "net/http" "time" ) func main() { resp, err := httpGetFromIP("https://httpbin.org/get", "127.0.0.1") if err != nil { fmt.Println(err) return } defer resp.Body.Close() bb, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(bb)) } func httpGetFromIP(url, ipaddr string) (*http.Response, error) { req, _ := http.NewRequest("GET", url, nil) client := &http.Client{ Transport: &http.Transport{ Dial: func(netw, addr string) (net.Conn, error) { lAddr, err := net.ResolveTCPAddr(netw, ipaddr+":0") if err != nil { return nil, err } rAddr, err := net.ResolveTCPAddr(netw, addr) if err != nil { return nil, err } conn, err := net.DialTCP(netw, lAddr,rAddr) if err != nil { return nil, err } deadline := time.Now().Add(35 * time.Second) conn.SetDeadline(deadline) return conn, nil }, }, } return client.Do(req) }

本文链接:https://troy.wang/post/go-httpclient.html

-- EOF --