-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (53 loc) · 1.26 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
package main
import (
"fmt"
"io"
"net/http"
"os"
"time"
)
func log(writer io.Writer, msg string) {
timestamp := time.Now().Format(time.RFC3339)
withTimestamp := fmt.Sprintf("%s: %s", timestamp, msg)
fmt.Fprint(writer, withTimestamp)
}
func main() {
endpointStr := os.Getenv("ENDPOINT")
if endpointStr == "" {
endpointStr = "https://checkip.amazonaws.com"
}
intervalStr := os.Getenv("INTERVAL")
if intervalStr == "" {
intervalStr = "1m"
}
interval, err := time.ParseDuration(intervalStr)
if err != nil {
log(os.Stderr, fmt.Sprintf("ERROR - Failed to parse interval value %s\n", intervalStr))
return
}
client := http.Client{
Timeout: 5 * time.Second,
}
for {
resp, err := client.Get(endpointStr)
if err != nil {
log(os.Stderr, "ERROR - Failed to make HTTP request.\n")
} else {
if resp.StatusCode != 200 {
log(os.Stderr, fmt.Sprintf("ERROR - HTTP request returned status code %d\n", resp.StatusCode))
} else {
body, err := io.ReadAll(resp.Body)
if err != nil {
log(os.Stderr, "ERROR - Failed to read response body.\n")
} else {
if len(body) > 0 && body[len(body)-1] != '\n' {
body = append(body, '\n')
}
log(os.Stdout, string(body))
}
}
resp.Body.Close()
}
time.Sleep(interval)
}
}