forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
64 lines (51 loc) · 1.12 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
package proxy
import (
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
)
func NewHandler(endpoints []string) (*httputil.ReverseProxy, error) {
d, err := newDirector(endpoints)
if err != nil {
return nil, err
}
proxy := httputil.ReverseProxy{
Director: d.direct,
Transport: &http.Transport{},
FlushInterval: 0,
}
return &proxy, nil
}
func newDirector(endpoints []string) (*director, error) {
if len(endpoints) == 0 {
return nil, errors.New("one or more endpoints required")
}
urls := make([]url.URL, len(endpoints))
for i, e := range endpoints {
u, err := url.Parse(e)
if err != nil {
return nil, fmt.Errorf("invalid endpoint %q: %v", e, err)
}
if u.Scheme == "" {
return nil, fmt.Errorf("invalid endpoint %q: scheme required", e)
}
if u.Host == "" {
return nil, fmt.Errorf("invalid endpoint %q: host empty", e)
}
urls[i] = *u
}
d := director{
endpoints: urls,
}
return &d, nil
}
type director struct {
endpoints []url.URL
}
func (d *director) direct(req *http.Request) {
choice := d.endpoints[0]
req.URL.Scheme = choice.Scheme
req.URL.Host = choice.Host
}