-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
87 lines (74 loc) · 1.48 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"errors"
"fmt"
"log"
"net/http"
"time"
)
func main() {
// Create 3 channels for each go routine
hits1 := make(chan string, 1)
hits2 := make(chan string, 1)
hits3 := make(chan string, 1)
// Create three go routines that will all ping the google server
for i := 0; i < 50; i++ {
go func() {
time, err := HitGoogle()
if err != nil {
log.Fatal(err)
}
hits1 <- time
}()
go func() {
time, err := HitGoogle()
if err != nil {
log.Fatal(err)
}
hits2 <- time
}()
go func() {
time, err := HitGoogle()
if err != nil {
log.Fatal(err)
}
hits3 <- time
}()
HITS_LOOP:
for {
select {
case time := <-hits1:
fmt.Println("Channel 1: " + time)
break HITS_LOOP
case time := <-hits2:
fmt.Println("Channel 2: " + time)
break HITS_LOOP
case time := <-hits3:
fmt.Println("Channel 3: " + time)
break HITS_LOOP
}
}
time.Sleep(time.Second * 1)
}
}
// HitGoogle will ping the google server once
func HitGoogle() (string, error) {
// Create a stopwatch
begin := time.Now()
res, err := http.Get("http://google.com")
if err != nil {
return "", err
}
defer res.Body.Close()
if res.Body == nil {
return "", errors.New("Response body was nil")
}
if res.StatusCode != 200 {
return "", errors.New("Expected response code 200")
}
// Get the end time for stopwatch
end := time.Now()
// Compare the two times to get result
totalTime := end.Sub(begin)
return totalTime.String(), err
}