-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (37 loc) · 1.24 KB
/
main.go
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
package main
import (
"fmt"
"io"
"net/http"
"sync"
)
func main() {
fmt.Println("Go routines")
endpoints := []string{
"https://jsonplaceholder.typicode.com/users/1",
"https://jsonplaceholder.typicode.com/todos/1",
"https://void-video-server.onrender.com/api/v1",
}
/*
A wait group is used to wait for all the go routines currently launched
finish their work
*/
waitGroup := sync.WaitGroup{}
defer waitGroup.Wait() // waits for the delta of wait group to become 0
for _, endpoint := range endpoints {
waitGroup.Add(1) // adds the delta 1 to waitgroup and when it becomes 0 all go routines are released
go makeAnApiCall(endpoint, &waitGroup) // Puts this call into a kindof separate thread managed by go runtime
// all api calls are launched at once - the time it takes the routine to finish may differ
}
}
func makeAnApiCall(endpoint string, wg *sync.WaitGroup) {
fmt.Println("Making an api call to:", endpoint)
defer wg.Done() // decrements waitgroup counter by one so the program may not get blocked forever
response, err := http.Get(endpoint)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, _ := io.ReadAll(response.Body)
fmt.Printf("The response from api: %s\n", bodyBytes)
}