I am trying to utilise goroutines in a golang GCP Cloud function and receive different results with and without the goroutine for idential code.
I am calling a function, 'Instance()', which makes an HTTPS GET request. If the function is called without a goroutine everything works as expected. If the function is called with a goroutine, 'go Instance()', I get a 'TLS handshake timeout' for the identical call.
I presume there is an issue with TLS and concurrency but cannot find any information.
func GoRoutineTest(w http.ResponseWriter, r *http.Request) {
defaultRoundTripper := http.DefaultTransport
defaultTransportPointer, ok := defaultRoundTripper.(*http.Transport)
if !ok {
panic(fmt.Sprintf("defaultRoundTripper not an *http.Transport"))
}
defaultTransport := *defaultTransportPointer // dereference it to get a copy of the struct that the pointer points to
defaultTransport.TLSHandshakeTimeout = 10 * time.Second
defaultTransport.MaxIdleConns = 100
defaultTransport.MaxIdleConnsPerHost = 100
client = &http.Client{Transport: &defaultTransport}
for i := 0; i < 8; i++ {
Instance() /* This works as expected */
go Instance() /* This fails with 'TLS handshake timeout' */
}
}
func Instance( ) {
resp, err := client.Get("https://google.com")
if err != nil {
fmt.Println(err)
} else {
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
}
fmt.Println(resp.StatusCode)
bodyString := string(bodyBytes)
fmt.Println(bodyString)
}
}
}