-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy.go
89 lines (81 loc) · 2.17 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
// Package proxy provides a simple proxy for a CouchDB server
package proxy
import (
"errors"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
// Proxy is an http.Handler which proxies connections to a CouchDB server.
type Proxy struct {
*httputil.ReverseProxy
// StrictMethods will reject any non-standard CouchDB methods immediately,
// rather than relaying to the CouchDB server.
StrictMethods bool
}
var _ http.Handler = &Proxy{}
// New returns a new Proxy instance, which redirects all requests to the
// specified URL.
func New(serverURL string) (*Proxy, error) {
if serverURL == "" {
return nil, errors.New("no URL specified")
}
target, err := url.Parse(serverURL)
if err != nil {
return nil, err
}
if target.User != nil {
return nil, errors.New("proxy URL must not contain auth credentials")
}
if target.RawQuery != "" {
return nil, errors.New("proxy URL must not contain query parameters")
}
director := func(req *http.Request) {
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
if _, ok := req.Header["User-Agent"]; !ok {
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}
}
return &Proxy{
ReverseProxy: &httputil.ReverseProxy{
Director: director,
},
}, nil
}
// Any other methods are rejected immediately, if StrictMethods is true.
var supportedMethods = []string{"GET", "HEAD", "POST", "PUT", "DELETE", "COPY"}
func (p *Proxy) methodAllowed(method string) bool {
if !p.StrictMethods {
return true
}
for _, m := range supportedMethods {
if m == method {
return true
}
}
return false
}
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !p.methodAllowed(r.Method) {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
p.ReverseProxy.ServeHTTP(w, r)
}
// singleJoiningSlash is copied from net/http/httputil/reverseproxy.go in the
// standard library.
func singleJoiningSlash(a, b string) string {
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}