-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
127 lines (104 loc) · 2.53 KB
/
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
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
package rproxy
import (
"fmt"
"net/http"
//"net/http/httputil"
//"net/url"
"github.com/vanng822/accesslog"
"github.com/vanng822/recovery"
)
type Server struct {
// Matching against req.Host
name string
backend *Backend
}
func (s *Server) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
s.backend.ServeHTTP(rw, req)
}
type Proxy struct {
servers map[string]*Server
conf *Conf
}
func NewProxy(conf *Conf) *Proxy {
p := &Proxy{}
p.servers = make(map[string]*Server)
if conf == nil {
conf = DefaultConf()
}
p.conf = conf
if conf.Servers != nil {
for _, s := range conf.Servers {
p.Register(s.ServerName, s.TargetUrl)
}
}
return p
}
func (p *Proxy) Start() {
logger := accesslog.New()
rec := recovery.NewRecovery()
http.Handle("/", rec.Handler(logger.Handler(p)))
if p.conf.ApiEnable {
api := p.AdminAPI()
go http.ListenAndServe(fmt.Sprintf("%s:%d", p.conf.ApiHost, p.conf.ApiPort), api)
}
http.ListenAndServe(fmt.Sprintf("%s:%d", p.conf.Host, p.conf.Port), nil)
}
func (p *Proxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if server, found := p.servers[req.Host]; found {
server.ServeHTTP(rw, req)
return
}
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
func (p *Proxy) ParseServerConfig(req *http.Request) (error, *ServerConfig) {
req.ParseForm()
serverName := req.Form.Get("serverName")
targetUrl := req.Form.Get("targetUrl")
if serverName == "" || targetUrl == "" {
return fmt.Errorf("You have to specify 'serverName' and 'targetUrl'"), nil
}
return nil, &ServerConfig{
ServerName: serverName,
TargetUrl: targetUrl,
}
}
func (p *Proxy) Register(serverName, targetUrl string) error {
var server *Server
if s, ok := p.servers[serverName]; ok {
server = s
} else {
server = &Server{
name: serverName,
backend: NewBackend(),
}
}
err := server.backend.addNode(targetUrl)
if err != nil {
return err
}
p.servers[serverName] = server
return nil
}
func (p *Proxy) Unregister(serverName, targetUrl string) error {
s, ok := p.servers[serverName]
if !ok {
return fmt.Errorf("No server by name %s", serverName)
}
err := s.backend.deleteNode(targetUrl)
if err != nil {
return err
}
// no nodes left then remove server
if len(s.backend.nodes) == 0 {
delete(p.servers, serverName)
}
return nil
}
func (p *Proxy) RemoveServer(serverName string) error {
_, ok := p.servers[serverName]
if !ok {
return fmt.Errorf("No server by name %s", serverName)
}
delete(p.servers, serverName)
return nil
}