-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-proxy.go
83 lines (73 loc) · 1.76 KB
/
reverse-proxy.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
package main
import (
"crypto/x509"
"encoding/json"
"flag"
ph "github.com/advptr/reverse-proxy/proxyhandler"
"io/ioutil"
"log"
"net/http"
)
// Main config
type Config struct {
TrustFiles []string `json:"trust-files"`
Routes []ph.Route `json:"routes""`
}
// Program Options
type Options struct {
ServerAddress string
ConfigFile string
}
// Main Bootstrap
func main() {
args := args()
config := config(args.ConfigFile)
trustedCertPool := config.trustedCertPool()
for _, r := range config.Routes {
handler := ph.NewWSHandler(r, trustedCertPool)
http.HandleFunc(handler.Path(), handler.Handle)
}
log.Printf("reverse-proxy on %v\n", args.ServerAddress)
err := http.ListenAndServe(args.ServerAddress, nil)
if err != nil {
panic(err)
}
}
// Parse command args
func args() Options {
const (
defaultServerAddress = ":80"
serverAddressUsage = "server address: ':80', '0.0.0.0:8080'..."
defaultRouteConfig = "config.json"
routeConfigUsage = "configuration file: 'config.json'"
)
address := flag.String("address", defaultServerAddress, serverAddressUsage)
config := flag.String("config", defaultRouteConfig, routeConfigUsage)
flag.Parse()
return Options{*address, *config}
}
//
func (c *Config) trustedCertPool() *x509.CertPool {
trustedCertPool := x509.NewCertPool()
for _, file := range c.TrustFiles {
trustedCert, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
trustedCertPool.AppendCertsFromPEM(trustedCert)
}
return trustedCertPool
}
// Unmarshal routes from JSON configuration file
func config(configFile string) Config {
file, err := ioutil.ReadFile(configFile)
if err != nil {
log.Fatal(err)
}
var config Config
err = json.Unmarshal(file, &config)
if err != nil {
log.Fatal(err)
}
return config
}