Requirement: worker goroutines concurrently send HTTPS(S) requests to various IPs. The URL and server IP are specified by the "main" routine in the parameter list when creating workers.
For instance: there are 100 worker goroutines requests https://www.google.com/ from different server IPs. The first worker asks for it from 1.1.1.1, and the second one does exactly the same thing but a different server IP (say 2.2.2.2).
Current solution: assign one http.Client with customized dial function in http.Transport for each routine.
go func(host, url string) {
defer wg.Done()
Client:=&http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
n, e := net.Dial("tcp", host)
fmt.Println(e)
return n, e
},
},
}
resp, err := Client.Get(url)
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
c, e := ioutil.ReadAll(resp.Body)
if e != nil {
return
}
fmt.Println(string(c))
}(realHost, url)
according to the godoc, Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.
Questions: So how can I fulfill my requirement by re-using the Client and transport?