-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
79 lines (67 loc) · 2.21 KB
/
Copy pathrequest.go
File metadata and controls
79 lines (67 loc) · 2.21 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 swt
import (
"bytes"
"context"
"net/http"
"github.com/gabriel-vasile/mimetype"
)
// Request represents a webhook request configuration for creating SecureWebhookTokens.
// It contains all the necessary information to build HTTP requests with embedded tokens.
type Request struct {
URL string // Target URL for the webhook request
Issuer string // JWT issuer claim (iss) - typically the service sending the webhook
Event string // Event name following EVENT_NAME.ACTIVITY format (e.g., "user.created")
HashAlg string // Hash algorithm for POST requests (SHA-256, SHA3-256, etc.). Defaults to SHA-256 if empty
Data []byte // Payload data to be sent with the request
}
// Build can be used to create a http.Request for creating and sending a
// SecureWebhookToken via POST method (the only allowed HTTP method for Secure Webhook Tokens).
func (r *Request) Build(key any, opts ...Option) (*http.Request, error) {
var (
claims WebhookClaims
req *http.Request
err error
)
claims = NewWebhookClaims(r.Issuer, r.Event)
if len(r.Data) > 0 {
hash, err := NewHash(r.HashAlg, r.Data)
if err != nil {
return nil, err
}
claims.Webhook.Hash = hash
}
swt, err := NewWithClaims(&claims, opts...)
if err != nil {
return nil, err
}
tokenStr, err := swt.SignedString(key)
if err != nil {
return nil, err
}
req, err = http.NewRequest(http.MethodPost, r.URL, bytes.NewReader(r.Data))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+tokenStr)
mType := mimetype.Detect(r.Data)
if mType != nil {
req.Header.Set("Content-Type", mType.String())
} else {
req.Header.Set("Content-Type", "application/octet-stream")
}
return req, nil
}
// BuildWithContext creates an http.Request with context support for creating and sending a
// SecureWebhookToken via POST method. The context can be used for cancellation and timeout control.
func (r *Request) BuildWithContext(ctx context.Context, key any, opts ...Option) (*http.Request, error) {
// Check context before doing any work
if err := ctx.Err(); err != nil {
return nil, err
}
req, err := r.Build(key, opts...)
if err != nil {
return nil, err
}
// Attach context to the request
return req.WithContext(ctx), nil
}