How-To-Implement-Concurrency-With-Goroutines-and-Channels

I wish I could be more like you.

Sequential Async Call

Let’s start with a basic console program that connects to a few website urls and tests if the connection is successful. There are no goroutines at start, and all calls are made in order which is not very efficient.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

import "fmt"
import "net/http"
import "time"

func main() {
start := time.Now()
links := []string {
"https://go.dev/learn/",
"https://www.netflix.com/",
"https://go.dev/learn/",
"https://www.netflix.com/",
"https://go.dev/learn/",
"https://www.netflix.com/",
"https://github.com/",
}

checkUrls(links)
fmt.Println("Completed the code process, took: %f seconds", time.Since(start).Seconds())
}

func checkUrls(urls []string) {
for _, link := range urls {
checkUrl(link)
}
}
func checkUrl(url string) {
_, err := http.Get(url)

if err != nil {
fmt.Println("We could not reach: ", url)
} else {
fmt.Println("Success reaching the website: ", url)
}
}

Adding Concurrency and Optimizing the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

package main

import "fmt"
import "sync"
import "net/http"
import "time"

func main() {
start := time.Now()
links := []string {
"https://go.dev/learn/",
"https://www.netflix.com/",
"https://go.dev/learn/",
"https://www.netflix.com/",
"https://go.dev/learn/",
"https://www.netflix.com/",
"https://github.com/",
}

checkUrls(links)
fmt.Println("Completed the code process, took: %f seconds", time.Since(start).Seconds())
}

func checkUrls(urls []string) {
c := make(chan string)
var wg sync.WaitGroup

for _, link := range urls {
wg.Add(1)
go checkUrl(link, c, &wg)
}

go func() {
wg.Wait()
close(c)
}()

for msg := range c {
fmt.Println(msg)
}
}


func checkUrl(url string, c chan string, wg *sync.WaitGroup) {
defer (*wg).Done()
_, err := http.Get(url)

if err != nil {
c <- "We could not reach: " + url
} else {
c <- "Success reaching the website: " + url
}
}

https://faun.pub/golang-tutorial-how-to-implement-concurrency-with-goroutines-and-channels-67d0f30d9e35