-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
85 lines (76 loc) · 1.61 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
package main
import (
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"syscall"
)
var socketPath = "/etc/udpproxy/api.sock"
func init() {
socketPathEnv := os.Getenv("SOCKET_PATH")
if socketPathEnv != "" {
socketPath = socketPathEnv
}
// create dir
err := os.MkdirAll(filepath.Dir(socketPath), 0755)
if err != nil {
log.Println("Failed to create directory")
log.Println(err)
os.Exit(1)
}
}
func main() {
// remove socket file
_ = os.Remove(socketPath)
server := newAPIServer()
// load records from file
records, err := ReadRecordsFromFile()
if err != nil {
log.Println("Failed to read records from file")
log.Println(err)
os.Exit(1)
}
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
// on SIGTERM, or SIGKILL, stop the server
go func() {
sig := <-sigs
go func() {
for sig := range sigs {
log.Printf("Already received %s, ignoring", sig)
}
}()
log.Printf("Received %s, stopping server", sig)
_ = server.Close()
log.Println("Server stopped")
log.Println("Stopping all proxies")
proxyManager.Close()
log.Println("Proxies stopped")
os.Exit(0)
}()
go func() {
// add records to manager
for _, record := range records {
_, err := proxyManager.Add(record)
if err != nil {
log.Println("Failed to add record")
log.Println(err)
}
}
}()
// start server
listener, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatal(err)
}
server.Listener = listener
httpServer := new(http.Server)
if err := server.StartServer(httpServer); err != nil {
log.Fatal(err)
}
// wait lifetime
select {}
}