-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (71 loc) · 1.44 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
)
type App struct {
Listen string `json:"listen"`
Backend BackendList `json:"backend"`
}
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if a.Backend.Check(r) {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
func (a *App) load(path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
if err := json.NewDecoder(file).Decode(a); err != nil {
return err
}
if a.Listen == "" {
a.Listen = ":1064"
}
return nil
}
func start(path string) error {
app := &App{}
if err := app.load(path); err != nil {
return fmt.Errorf("config: %w", err)
}
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
server := http.Server{
Addr: app.Listen,
Handler: app,
}
go func() {
<-signalCh
server.Close()
}()
if err := server.ListenAndServe(); err != http.ErrServerClosed {
return err
}
return nil
}
func main() {
configPath := "/etc/auth-proxy.conf"
if len(os.Args) > 1 {
configPath = os.Args[1]
switch configPath {
case "help", "-h", "--help":
fmt.Fprintf(os.Stdout, "Usage: %s [config]\n", os.Args[0])
os.Exit(0)
case "version", "-v", "--version":
fmt.Fprintf(os.Stdout, "Auth Proxy v0\n")
os.Exit(0)
}
}
if err := start(configPath); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
}