-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
97 lines (77 loc) · 2.06 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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/spf13/viper"
)
type Location struct {
// Where to dispatch the request
URL string
}
type HttpConfig struct {
Address string
Port int
}
type Config struct {
Locations map[string][]Location
Http HttpConfig
}
func dispatch(cfg Config) http.HandlerFunc {
client := http.Client{}
return func(w http.ResponseWriter, r *http.Request) {
locations, ok := cfg.Locations[r.URL.Path]
if !ok {
log.Printf("Unconfigured URL path got called: %s", r.URL.Path)
http.NotFound(w, r)
return
}
var bodyBytes []byte
if r.Body != nil {
bodyBytes, _ = ioutil.ReadAll(r.Body)
}
log.Printf("Dispatching request for path: %s", r.URL.Path)
var i int
for _, location := range locations {
req, err := http.NewRequest(r.Method, location.URL, ioutil.NopCloser(bytes.NewBuffer(bodyBytes)))
if err != nil {
log.Printf("Invalid request in config for path %s: %s", r.URL.Path, err)
continue
}
req.Header = r.Header
req.Form = r.Form
req.ContentLength = r.ContentLength
_, err = client.Do(req)
if err != nil {
log.Printf("Request failed: %s", err)
continue
}
i += 1
}
log.Printf("Sent request for path %s to %v/%v locations", r.URL.Path, i, len(locations))
w.Write([]byte("OK\n"))
}
}
func main() {
cfg := LoadConfig()
http.Handle("/", dispatch(cfg))
log.Printf("Listening on address %s:%v", cfg.Http.Address, cfg.Http.Port)
log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%v", cfg.Http.Address, cfg.Http.Port), nil))
}
func LoadConfig() (config Config) {
viper.SetConfigName("config")
viper.SetConfigType("json")
viper.AddConfigPath(".")
viper.AutomaticEnv()
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file: %s", err)
}
viper.SetDefault("http.address", "0.0.0.0")
viper.SetDefault("http.port", "8080")
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("Unable to decode configuration file: %s", err)
}
return
}