-
Notifications
You must be signed in to change notification settings - Fork 307
/
event.go
108 lines (95 loc) · 2.17 KB
/
event.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
100
101
102
103
104
105
106
107
108
package commands
import (
"bytes"
"embed"
"fmt"
"io"
"net/http"
"text/template"
"time"
"github.com/google/uuid"
"github.com/rudderlabs/rudder-server/utils/httputil"
"github.com/urfave/cli/v2"
)
func init() {
DefaultList = append(DefaultList, EVENT())
}
//go:embed payloads/*
var payloads embed.FS
func EVENT() *cli.Command {
c := &cli.Command{
Name: "event",
Usage: "collection of commands to help with event testing",
Subcommands: []*cli.Command{
{
Name: "send",
Usage: "send event to rudder-server",
Action: EventSend,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "endpoint",
Usage: "HTTP endpoint for rudder-server",
Value: "http://localhost:8080",
},
&cli.StringFlag{
Name: "write-key",
Usage: "source write key",
Required: true,
},
&cli.IntFlag{
Name: "count",
Usage: "number of events to send",
Value: 1,
},
},
ArgsUsage: "",
},
},
}
return c
}
func EventSend(c *cli.Context) error {
client := &http.Client{}
url := fmt.Sprintf("%s/v1/batch", c.String("endpoint"))
t, err := template.New("batch.json").ParseFS(payloads, "payloads/batch.json")
if err != nil {
return err
}
for i := 0; i < c.Int("count"); i++ {
if err := func() error {
anonymousId := uuid.New().String()
buf := bytes.NewBuffer(nil)
err = t.Execute(buf, map[string]string{
"AnonymousId": anonymousId,
"Timestamp": time.Now().Format(time.RFC3339),
})
if err != nil {
return err
}
req, err := http.NewRequestWithContext(c.Context, "POST", url, buf)
if err != nil {
return err
}
req.SetBasicAuth(c.String("write-key"), "")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("AnonymousId", anonymousId)
resp, err := client.Do(req)
if err != nil {
return err
}
defer func() { httputil.CloseResponse(resp) }()
b, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
fmt.Printf("%s\n%s\n", resp.Status, b)
return fmt.Errorf("status code: %d", resp.StatusCode)
}
return nil
}(); err != nil {
return err
}
}
return nil
}