-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhttp.go
82 lines (64 loc) · 1.31 KB
/
http.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
package templar
import (
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
)
const UpgradeHeader = "X-Templar-Upgrade"
func NewHTTPTransport() Transport {
return &HTTPTransport{
&http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
},
}
}
type HTTPTransport struct {
h Transport
}
func (h *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
out := &http.Request{}
*out = *req
out.RequestURI = ""
out.Header = make(http.Header)
for k, v := range req.Header {
if strings.HasPrefix(k, TemplarPrefix) {
if k == UpgradeHeader && v[0] == "https" {
u := &url.URL{}
*u = *out.URL
u.Scheme = "https"
out.URL = u
}
continue
}
out.Header[k] = v
}
return h.h.RoundTrip(out)
}
func (h *HTTPTransport) CancelRequest(req *http.Request) {
h.h.CancelRequest(req)
}
func CopyResponse(res http.ResponseWriter, upstream *http.Response) {
for k, v := range upstream.Header {
res.Header()[k] = v
}
res.WriteHeader(upstream.StatusCode)
if upstream.Body != nil {
io.Copy(res, upstream.Body)
upstream.Body.Close()
}
}
func CopyBody(dst io.Writer, src io.Reader) {
if src != nil {
io.Copy(dst, src)
}
if fin, ok := dst.(Finisher); ok {
fin.Finish()
}
}