-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevents.go
More file actions
63 lines (55 loc) · 1.34 KB
/
events.go
File metadata and controls
63 lines (55 loc) · 1.34 KB
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
package loops
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type SendEventRequest struct {
Email string `json:"-"`
UserID string `json:"-"`
EventName string `json:"-"`
EventProperties map[string]any `json:"-"`
MailingLists map[string]bool `json:"-"`
ContactProperties map[string]any `json:"-"`
IdempotencyKey string `json:"-"`
}
func (c *Client) SendEvent(req SendEventRequest) error {
body := make(map[string]any)
for k, v := range req.ContactProperties {
body[k] = v
}
body["eventName"] = req.EventName
if req.Email != "" {
body["email"] = req.Email
}
if req.UserID != "" {
body["userId"] = req.UserID
}
if len(req.EventProperties) > 0 {
body["eventProperties"] = req.EventProperties
}
if len(req.MailingLists) > 0 {
body["mailingLists"] = req.MailingLists
}
b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to encode request: %w", err)
}
httpReq, err := c.newRequest(http.MethodPost, "/events/send", bytes.NewReader(b))
if err != nil {
return err
}
if req.IdempotencyKey != "" {
httpReq.Header.Set("Idempotency-Key", req.IdempotencyKey)
}
resp, err := c.do(httpReq)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errorFromResponse(resp)
}
return nil
}