Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
117 lines (98 loc) · 2.29 KB
/
Copy pathmain.go
File metadata and controls
117 lines (98 loc) · 2.29 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
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
108
109
110
111
112
113
114
115
116
117
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"time"
)
const (
key = "msg"
retryDuration = 2 * time.Second
)
func main() {
var (
accountID, namespaceID, apiToken string
exists bool
)
accountID, exists = os.LookupEnv("CLOUDFLARE_ACCOUNT_ID")
if !exists {
panic("set CLOUDFLARE_ACCOUNT_ID env")
}
namespaceID, exists = os.LookupEnv("CLOUDFLARE_NAMESPACE_ID")
if !exists {
panic("set CLOUDFLARE_NAMESPACE_ID env")
}
apiToken, exists = os.LookupEnv("CLOUDFLARE_API_TOKEN")
if !exists {
panic("set CLOUDFLARE_API_TOKEN env")
}
t := time.NewTicker(retryDuration)
defer t.Stop()
var value string
for {
v := getAndDeleteKey(key, accountID, namespaceID, apiToken)
if len(v) > 0 {
value = v
break
}
<-t.C
log.Println("Key not found, retrying...")
}
if err := exec.Command("halp", "-m", value); err != nil {
log.Fatalf("error executing halp command: %v\n", err)
}
}
func getAndDeleteKey(key, accountID, namespaceID, apiToken string) string {
url := fmt.Sprintf(
"https://api.cloudflare.com/client/v4/accounts/%s/storage/kv/namespaces/%s/values/%s",
accountID, namespaceID, key,
)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode == 404 {
return "" // blank string indicates retry
}
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Error: %s\n", string(body))
os.Exit(1)
}
value, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
deleteKey(key, accountID, namespaceID, apiToken)
return string(value)
}
func deleteKey(key, accountID, namespaceID, apiToken string) {
url := fmt.Sprintf(
"https://api.cloudflare.com/client/v4/accounts/%s/storage/kv/namespaces/%s/values/%s",
accountID, namespaceID, key,
)
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+apiToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
body, _ := io.ReadAll(resp.Body)
fmt.Printf("Error: %s\n", string(body))
os.Exit(1)
}
}