-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgreenlight.go
66 lines (56 loc) · 1.45 KB
/
greenlight.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
package signup
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type greenlightService struct {
url string // URL to POST webhooks.
apiKey string // Token to make Greenlight API requests.
}
func NewGreenlightService(url, apiKey string) *greenlightService {
return &greenlightService{
url: url,
apiKey: apiKey,
}
}
func (g greenlightService) run(ctx context.Context, su Signup) error {
return g.postWebhook(ctx, su)
}
// IsRequired return true because the signup record in Greenlight is needed by staff.
func (g greenlightService) isRequired() bool {
return true
}
func (g greenlightService) name() string {
return "greenlight service"
}
// PostWebhook sends a webhook to Greenlight (POST /signup).
// The webhook creates a Info Session Signup record in the Greenlight database.
func (g greenlightService) postWebhook(ctx context.Context, su Signup) error {
reqBody, err := json.Marshal(su)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
g.url,
bytes.NewBuffer(reqBody),
)
if err != nil {
return fmt.Errorf("newRequest: %w", err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Greenlight-Signup-Api-Key", g.apiKey)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("POST request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return handleHTTPError(resp)
}
return nil
}