-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
117 lines (94 loc) · 2.57 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
108
109
110
111
112
113
114
115
116
117
// Copyright 2024 Blues Inc. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
package main
import (
"bufio"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
// Main service entry point
func main() {
// Register endpoint for udp-proxy.net lookups, which are
// performed when notehub starts up so that it knows
// what IP:PORT to issue to devices.
http.HandleFunc("/", httpProxyLookupHandler)
// Register the UDP proxy handlers, which are used by devices
// to send messages to the notehub - proxied to HTTP by us here.
go udpProxyHandlers()
// Register AWS health check endpoint
http.HandleFunc("/ping", httpPingHandler)
go func() {
if err := http.ListenAndServe(":80", nil); err != nil {
loggedExit(41, "Error starting HTTP listener:", err)
}
}()
// Spawn our signal handler
go signalHandler()
// Handle console input so we can manually quit and relaunch
go inputHandler()
// Hearbeat
for {
fmt.Println(getNowTimestamp(), "heartbeat")
time.Sleep(300 * time.Second)
}
}
func loggedExit(code int, message ...any) {
fmt.Print(getNowTimestamp(), " ")
fmt.Println(message...)
fmt.Println(getNowTimestamp(), "Exiting with code", code)
os.Stdout.Sync()
os.Exit(code)
}
func getNowTimestamp() string {
return time.Now().UTC().Format("2006-01-02T15:04:05Z")
}
// Ping handler, for AWS health checks
func httpPingHandler(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(getNowTimestamp()))
if traceIo {
fmt.Println(getNowTimestamp(), r.RemoteAddr, "PING")
}
}
func inputHandler() {
scanner := bufio.NewScanner(os.Stdin)
// Loops indefinitely, waiting for input unless Stdin gets an error or EOF
for scanner.Scan() {
message := scanner.Text()
args := strings.Split(message, " ")
switch args[0] {
case "q":
os.Exit(0)
case "":
// just re-prompt
default:
fmt.Printf("Unrecognized: '%s'\n", message)
}
fmt.Print("\n> ")
}
err := scanner.Err()
if err != nil {
fmt.Println(getNowTimestamp(), "Input handler shutting down due to error", err)
} else {
fmt.Println(getNowTimestamp(), "Input handler shutting down due to EOF")
}
}
// Our app's signal handler
func signalHandler() {
ch := make(chan os.Signal, 100)
signal.Notify(ch, syscall.SIGTERM)
signal.Notify(ch, syscall.SIGINT)
signal.Notify(ch, syscall.SIGSEGV)
signal := <-ch
exitCode := 1
switch signal {
case syscall.SIGINT, syscall.SIGTERM:
exitCode = 0
}
loggedExit(exitCode, getNowTimestamp(), "*** Exiting because of SIGNAL", signal)
}