I\'m currently struggling to find a way to reuse connections when making HTTP posts in Golang.
I\'ve created a transport and client like so:
// Crea
Another approach to init()
is to use a singleton method to get the http client. By using sync.Once you can be sure that only one instance will be used on all your requests.
var (
once sync.Once
netClient *http.Client
)
func newNetClient() *http.Client {
once.Do(func() {
var netTransport = &http.Transport{
Dial: (&net.Dialer{
Timeout: 2 * time.Second,
}).Dial,
TLSHandshakeTimeout: 2 * time.Second,
}
netClient = &http.Client{
Timeout: time.Second * 2,
Transport: netTransport,
}
})
return netClient
}
func yourFunc(){
URL := "local.dev"
req, err := http.NewRequest("POST", URL, nil)
response, err := newNetClient().Do(req)
// ...
}