-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathupstream.go
97 lines (72 loc) · 1.58 KB
/
upstream.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
90
91
92
93
94
95
96
97
package templar
import (
"errors"
"net/http"
"time"
)
const TemplarPrefix = "X-Templar-"
type Upstream struct {
transport Transport
stats Stats
}
func NewUpstream(client Transport, stats Stats) *Upstream {
return &Upstream{client, stats}
}
const CTimeoutHeader = "X-Templar-Timeout"
func (t *Upstream) extractTimeout(req *http.Request) (time.Duration, bool) {
header := req.Header.Get(CTimeoutHeader)
if header == "" {
return 0, false
}
dur, err := time.ParseDuration(header)
if err != nil {
return 0, false
}
return dur, true
}
func (t *Upstream) forward(res Responder, req *http.Request) error {
upstream, err := t.transport.RoundTrip(req)
if err != nil {
return err
}
w := res.Send(upstream)
CopyBody(w, upstream.Body)
return err
}
var ErrTimeout = errors.New("request timed out")
func (t *Upstream) Forward(res Responder, req *http.Request) error {
dur, ok := t.extractTimeout(req)
if !ok {
return t.forward(res, req)
}
fin := make(chan error)
go func() {
fin <- t.forward(res, req)
}()
time.AfterFunc(dur, func() {
t.transport.CancelRequest(req)
fin <- ErrTimeout
})
err := <-fin
if err == ErrTimeout {
t.stats.RequestTimeout(req, dur)
if fb, ok := t.transport.(Fallback); ok {
upstream, err := fb.Fallback(req)
if err != nil {
return err
}
if upstream != nil {
CopyBody(res.Send(upstream), upstream.Body)
return nil
}
}
uperr := &http.Response{
Request: req,
StatusCode: 504,
Header: make(http.Header),
}
uperr.Header.Set("X-Templar-TimedOut", "true")
res.Send(uperr)
}
return nil
}