-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
107 lines (76 loc) · 1.89 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"github.com/aws/aws-lambda-go/lambda"
)
type TickerEvent struct {
Frequency string `json:"frequency"`
}
type PeriodicWorkData struct {
Frequency string `json:"frequency"`
}
func handler(event TickerEvent) error {
env, err := NewEnv()
if err != nil {
return err
}
data := PeriodicWorkData(event)
dataJson, err := json.Marshal(data)
if err != nil {
return err
}
response, err := callPeriodicWork(dataJson, env.EngineHostname, env.EngineSecret)
if err != nil {
return err
}
if response.StatusCode != 200 {
return fmt.Errorf("engine: %d", response.StatusCode)
}
return nil
}
type Env struct {
EngineHostname string
EngineSecret string
}
const engineHostnameKey = "ENGINE_HOSTNAME"
const engineSecretKey = "ENGINE_SECRET"
func NewEnv() (Env, error) {
engineHostname, err := validateEnv(engineHostnameKey)
if err != nil {
return Env{}, err
}
engineSecret, err := validateEnv(engineSecretKey)
if err != nil {
return Env{}, err
}
return Env{EngineHostname: engineHostname, EngineSecret: engineSecret}, nil
}
func validateEnv(key string) (string, error) {
value, present := os.LookupEnv(key)
if !present {
return "", fmt.Errorf("%v env var is not present", key)
}
return value, nil
}
func callPeriodicWork(dataJson []byte, engineHostname string, engineSecret string) (*http.Response, error) {
url := fmt.Sprintf("https://%s/admin/periodic-work", engineHostname)
request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(dataJson))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Authorization", fmt.Sprintf("Bearer %v", engineSecret))
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
return response, nil
}
func main() {
lambda.Start(handler)
}