-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
99 lines (80 loc) · 2.12 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
88
89
90
91
92
93
94
95
96
97
98
99
/* Concurrent Data Fetcher in Go: Fetching Data Concurrently from APIs */
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sync"
"time"
)
type Todo struct {
TaskName string `json:"taskName"`
Completed bool `json:"completed"`
}
type Request struct {
Method string
Endpoint string
Data interface{}
}
func fetchData(req Request, wg *sync.WaitGroup, ch chan<- string) {
defer wg.Done()
var resp *http.Response
var err error
client := &http.Client{
Timeout: 4 * time.Second,
}
if req.Method == "POST" { // POST
jsonData, err := json.Marshal(req.Data)
if err != nil {
ch <- fmt.Sprintf("error %s: %v", req.Endpoint, err)
return
}
resp, err = client.Post(req.Endpoint, "application/json", bytes.NewBuffer(jsonData))
} else {
resp, err = client.Get(req.Endpoint) // GET
}
if err != nil {
ch <- fmt.Sprintf("error %s: %v", req.Endpoint, err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
ch <- fmt.Sprintf("error %s: %v", req.Endpoint, err)
return
}
ch <- fmt.Sprintf("\nResponse from '%s' %s:\n\n %s\n", req.Method, req.Endpoint, body)
time.Sleep(500 * time.Millisecond)
}
func main() {
//t := true
endpoints := []Request{
{Method: "GET", Endpoint: "http://localhost:8090/cloudvendor/1"},
{Method: "GET", Endpoint: "http://localhost:8090/cloudvendor/todo/1/getTodo"},
{Method: "POST", Endpoint: "http://localhost:8090/cloudvendor/addVendor", Data: map[string]string{
"vendorName": "Roman Cali",
"vendorEmail": "[email protected]",
}},
{Method: "POST", Endpoint: "http://localhost:8090/cloudvendor/todo/2/addTodo", Data: Todo{
TaskName: "Finish shopping clothes",
Completed: true,
}},
}
numRequests := len(endpoints)
ch := make(chan string, numRequests)
var wg sync.WaitGroup
wg.Add(numRequests)
for i := 0; i < numRequests; i++ {
go fetchData(endpoints[i], &wg, ch)
}
go func() {
wg.Wait()
close(ch)
}()
for result := range ch {
fmt.Println(result)
}
fmt.Println("Main has Ended!")
}