How to create goroutines in Golang?


Added the go keyword before each call of function responseSize. The three responseSize goroutines starts up concurrently and three calls to http.Get are made concurrently as well. The program doesn't wait until one response comes back before sending out the next request. As a result the three response sizes are printed much sooner using goroutines.

We have added a call to time.Sleep in the main function which prevents the main goroutine from exiting before the responseSize goroutines can finish. Calling time.Sleep(10 * time.Second) will make the main goroutine to sleep for 10 seconds.

Example

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

func responseSize(url string) {
	fmt.Println("Step1: ", url)
	response, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Step2: ", url)
	defer response.Body.Close()

	fmt.Println("Step3: ", url)
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Step4: ", len(body))
}

func main() {
	go responseSize("https://www.golangprograms.com")
	go responseSize("https://coderwall.com")
	go responseSize("https://stackoverflow.com")
	time.Sleep(10 * time.Second)
}

Output

Step1:  https://www.golangprograms.com
Step1:  https://stackoverflow.com
Step1:  https://coderwall.com
Step2:  https://stackoverflow.com
Step3:  https://stackoverflow.com
Step4:  116749
Step2:  https://www.golangprograms.com
Step3:  https://www.golangprograms.com
Step4:  79551
Step2:  https://coderwall.com
Step3:  https://coderwall.com
Step4:  203842
Most Helpful This Week