-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
63 lines (50 loc) · 1.14 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
package main
import (
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"sync"
)
type BufferPool sync.Pool
func (p *BufferPool) Get() []byte {
return (*sync.Pool)(p).Get().([]byte)
}
func (p *BufferPool) Put(b []byte) {
(*sync.Pool)(p).Put(b)
}
var bufferPool = BufferPool{
New: func() interface{} {
return make([]byte, 32*1024)
},
}
func NewProxy(routes map[string]Route, defaultRoute string) *httputil.ReverseProxy {
defUrl, _ := url.Parse(defaultRoute)
director := func(req *http.Request) {
log.Printf("%s %s%s\n", req.Method, req.Host, req.URL.String())
addrStr, _, _ := net.SplitHostPort(req.RemoteAddr)
ip := net.ParseIP(addrStr)
req.Header.Set("Forwarded", "for="+ip.String())
req.Header.Set("X-Forwarded-For", ip.String())
route, ok := routes[req.Host]
if !ok {
req.URL.Host = defUrl.Host
req.URL.Scheme = defUrl.Scheme
req.Host = defUrl.Host
return
}
u, err := url.Parse(route.Host)
if err != nil {
log.Println(err)
return
}
req.URL.Host = u.Host
req.URL.Scheme = u.Scheme
req.Host = u.Host
}
return &httputil.ReverseProxy{
Director: director,
BufferPool: &bufferPool,
}
}