-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebhook.go
More file actions
79 lines (74 loc) · 2.05 KB
/
Copy pathwebhook.go
File metadata and controls
79 lines (74 loc) · 2.05 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package inboundgo
import (
"encoding/json"
"fmt"
"io"
)
// ParseWebhookPayload parses an incoming webhook payload into the WebhookPayload struct
func ParseWebhookPayload(reader io.Reader) (*WebhookPayload, error) {
var payload WebhookPayload
decoder := json.NewDecoder(reader)
err := decoder.Decode(&payload)
if err != nil {
return nil, fmt.Errorf("failed to parse webhook payload: %w", err)
}
return &payload, nil
}
// GetFromAddress extracts the properly formatted from address from the webhook
func (w *WebhookPayload) GetFromAddress() string {
if w.Email.From != nil && len(w.Email.From.Addresses) > 0 {
addr := w.Email.From.Addresses[0]
if addr.Address == nil {
return ""
}
if addr.Name != nil && *addr.Name != "" {
return fmt.Sprintf("%s <%s>", *addr.Name, *addr.Address)
}
return *addr.Address
}
return ""
}
// GetToAddress extracts the properly formatted to address from the webhook
func (w *WebhookPayload) GetToAddress() string {
if w.Email.To != nil && len(w.Email.To.Addresses) > 0 {
addr := w.Email.To.Addresses[0]
if addr.Address == nil {
return ""
}
if addr.Name != nil && *addr.Name != "" {
return fmt.Sprintf("%s <%s>", *addr.Name, *addr.Address)
}
return *addr.Address
}
return ""
}
// GetHeaders converts the headers from the webhook format to a standard map[string][]string format
func (w *WebhookPayload) GetHeaders() map[string][]string {
headers := make(map[string][]string)
for k, v := range w.Email.ParsedData.Headers {
switch val := v.(type) {
case string:
headers[k] = []string{val}
case []string:
headers[k] = val
case []any:
var strSlice []string
for _, item := range val {
if str, ok := item.(string); ok {
strSlice = append(strSlice, str)
}
}
if len(strSlice) > 0 {
headers[k] = strSlice
}
case map[string]any:
// Handle complex header structures like dkim-signature
if text, ok := val["text"].(string); ok {
headers[k] = []string{text}
} else if value, ok := val["value"].(string); ok {
headers[k] = []string{value}
}
}
}
return headers
}