-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
135 lines (117 loc) · 3.02 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main
import (
"flag"
"fmt"
"github.com/intrip/golang-load-balancer/common"
"github.com/spf13/viper"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
"time"
)
var (
bind, balance string
port, maxConnections int
readTimeout = 10
writeTimeout = 10
backends []common.Backend
testEnv bool
)
func init() {
loadConfig("config")
if flag.Lookup("test.v") == nil {
testEnv = false
} else {
testEnv = true
}
}
// loads config from ./config.yaml
func loadConfig(config string) {
viper.SetConfigType("yaml")
viper.SetConfigName(config)
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Error in config file: %s \n", err))
}
server := viper.GetStringMapString("server")
// read port
if v, ok := server["port"]; ok {
port, err = strconv.Atoi(v)
if err != nil {
panic(fmt.Errorf("Server port is not valid: %s \n", err))
}
} else {
panic(fmt.Errorf("Server port is required"))
}
// listen
if v, ok := server["bind"]; ok {
bind = v
} else {
panic(fmt.Errorf("Server bind is required"))
}
// maxConnections
if v, ok := server["maxconnections"]; ok {
maxConnections, err = strconv.Atoi(v)
if err != nil {
panic(fmt.Errorf("Server maxConnections is not valid: %s \n", err))
}
} else {
panic(fmt.Errorf("Server maxConnections is required"))
}
// timeout
if v, ok := server["readtimeout"]; ok {
readTimeout, err = strconv.Atoi(v)
if err != nil {
panic(fmt.Errorf("server readtimeout is not valid: %s \n", err))
}
}
if v, ok := server["writetimeout"]; ok {
writeTimeout, err = strconv.Atoi(v)
if err != nil {
panic(fmt.Errorf("server writetimeout is not valid: %s \n", err))
}
}
balance = viper.GetString("balancers")
backends = parseBalance(balance)
}
func main() {
s := &http.Server{
Addr: serverUrl(),
Handler: common.NewLimitHandler(maxConnections, &Proxy{&common.RoundRobin{0, backends}}),
ReadTimeout: time.Duration(readTimeout) * time.Second,
WriteTimeout: time.Duration(writeTimeout) * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
func serverUrl() string {
return fmt.Sprintf("%s:%d", bind, port)
}
type Proxy struct{ backendStruct *common.RoundRobin }
func (h *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
next := common.Next(h.backendStruct)
doBalance(w, r, &next)
}
func doBalance(w http.ResponseWriter, r *http.Request, backend *common.Backend) {
u, err := url.Parse(backend.Url)
if err != nil {
log.Panic("Error parsing backend Url: ", err)
}
if !testEnv {
log.Printf("Request from: %s forwarded to: %s path: %s", r.RemoteAddr, backend.Url, r.RequestURI)
}
proxy := httputil.NewSingleHostReverseProxy(u)
proxy.ServeHTTP(w, r)
}
func parseBalance(balancers string) (backends []common.Backend) {
urls := strings.Split(balancers, ",")
backends = make([]common.Backend, len(urls))
for index, backend := range urls {
backends[index] = common.Backend{Url: backend, ActiveConnections: 0}
}
return
}