-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathclient.go
76 lines (62 loc) · 1.35 KB
/
client.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
package main
import (
"bytes"
"encoding/json"
"errors"
"io"
"log"
"math/rand"
"net/http"
"runtime"
"time"
)
var (
errClientError = errors.New("client error")
)
const (
defaultTimeout = 5 * time.Second
)
func getRandomEvent() string {
events := []string{"create", "update", "remove", "clear"}
index := rand.Intn(3)
return events[index]
}
func callServer(ticker *time.Ticker) {
for range ticker.C {
event := getRandomEvent()
log.Printf("sending event %s to the webhook\n", event)
client := http.Client{}
req, err := http.NewRequest(http.MethodPost, "http://localhost:8000/webhook", nil)
if err != nil {
log.Fatal(err)
continue
}
req.Header.Add("Accept", "application/json; charset=UTF-8")
reqPayload := Event{Event: getRandomEvent()}
jsonData, err := json.Marshal(reqPayload)
if err != nil {
log.Fatal(err)
continue
}
req.Body = io.NopCloser(bytes.NewBuffer(jsonData))
res, err := client.Do(req)
if err != nil {
log.Fatal(err)
continue
}
body, err := io.ReadAll(res.Body)
defer res.Body.Close()
if err != nil {
log.Fatal(err)
continue
}
log.Printf("response: %s", string(body))
}
}
func main() {
ticker := time.NewTicker(defaultTimeout)
go callServer(ticker)
// Terminates the main goroutine without main() returning.
// This effectively runs the main() forever.
runtime.Goexit()
}