This repository has been archived by the owner on May 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
proxy.go
73 lines (67 loc) · 1.85 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
package main
import (
"context"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
)
// ReverseProxyConfig configuration settings for a proxy instance
type ReverseProxyConfig struct {
ConnectTimeout time.Duration
Timeout time.Duration
IdleTimeout time.Duration
}
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
}
// NewSingleHostReverseProxy creates a new reverse proxy instance
func NewSingleHostReverseProxy(target *url.URL, conf ReverseProxyConfig) http.Handler {
targetQuery := target.RawQuery
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 targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
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 &httputil.ReverseProxy{
FlushInterval: 200 * time.Millisecond,
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (conn net.Conn, e error) {
// open conn
c, err := net.DialTimeout(network, addr, conf.ConnectTimeout)
if err != nil {
return c, err
}
// set read/write timeout
if err := c.SetDeadline(time.Now().Add(conf.Timeout)); err != nil {
return c, err
}
return c, err
},
TLSHandshakeTimeout: 10 * time.Second,
IdleConnTimeout: conf.IdleTimeout,
MaxResponseHeaderBytes: 1 << 20,
DisableCompression: true,
},
Director: director,
}
}