-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (93 loc) · 2.33 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
package main
import (
"encoding/json"
"flag"
"io"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
var (
configFlag = flag.String("cfg", "config.json", "path to config file")
listenAddrFlag = flag.String("http", "127.0.0.1:5000", "forwarding http listen addr")
)
var (
configMu sync.RWMutex
config = make(map[string]string)
)
func main() {
flag.Parse()
if err := loadConfig(); err != nil {
os.Exit(1)
}
forwardClient := http.Client{Timeout: 5 * time.Second}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
configMu.RLock()
target, ok := config[r.URL.Path]
configMu.RUnlock()
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
log.Printf("got request %q -> %q", r.URL.Path, target)
resp, err := forwardClient.Get(target)
if err != nil {
log.Printf("forward: request failed: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
w.WriteHeader(resp.StatusCode)
if _, err := io.Copy(w, resp.Body); err != nil {
log.Printf("forward: failed to copy response: %v", err)
}
})
go handleSignals()
log.Printf("http: starting server at %q...", *listenAddrFlag)
if err := http.ListenAndServe(*listenAddrFlag, nil); err != nil {
log.Printf("http listener on %q failed: %v", *listenAddrFlag, err)
os.Exit(2)
}
}
func loadConfig() error {
log.Printf("loading config from %q", *configFlag)
bs, err := os.ReadFile(*configFlag)
if err != nil {
log.Printf("failed to open config file at %q: %v", *configFlag, err)
return err
}
cfg := make(map[string]string)
if err := json.Unmarshal(bs, &cfg); err != nil {
log.Printf("failed to load config file content: %v", err)
return err
}
log.Printf("loaded %d entities from config file", len(cfg))
configMu.Lock()
defer configMu.Unlock()
config = cfg
return nil
}
func handleSignals() {
reload := make(chan os.Signal, 1)
signal.Notify(reload, syscall.SIGUSR1, syscall.SIGUSR2)
terminate := make(chan os.Signal, 1)
signal.Notify(terminate, syscall.SIGTERM)
for {
select {
case sig := <-reload:
log.Printf("got %q signal, reloading config...", sig.String())
_ = loadConfig()
case sig := <-terminate:
log.Printf("got %q signal, exiting...", sig)
os.Exit(0)
}
}
}