-
Notifications
You must be signed in to change notification settings - Fork 2
/
agent.go
65 lines (53 loc) · 1.41 KB
/
agent.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
package fakepoint
import (
"net/http"
)
func NewAgent() *Agent {
return &Agent{
fakepoints: make(map[string]*Fakepoint),
fakepointsCount: make(map[string]int),
}
}
type Agent struct {
maker *FakepointMaker
fakepoints map[string]*Fakepoint
fakepointsCount map[string]int
}
func (a Agent) RoundTrip(r *http.Request) (*http.Response, error) {
key := a.getKey(*r)
if fakepoint := a.fakepoints[key]; fakepoint != nil {
roundTrip := http.RoundTripper(*fakepoint)
resp, err := roundTrip.RoundTrip(r)
a.resolveCount(roundTrip.(Fakepoint))
return resp, err
}
return FourOFour(), nil
}
func (a Agent) add(url, method string, roundTrip *Fakepoint) {
roundTrip.agent = &a
key := a.makeKey(url, method)
a.fakepoints[key] = roundTrip
a.fakepointsCount[key] = 1
}
func (a Agent) increaseCount(url, method string, num int) {
key := a.makeKey(url, method)
a.fakepointsCount[key] += num
}
func (a Agent) resolveCount(roundTrip Fakepoint) {
key := a.makeKey(roundTrip.url, roundTrip.method)
a.fakepointsCount[key]--
if a.fakepointsCount[key] == 0 {
a.remove(roundTrip)
}
}
func (a Agent) remove(roundTrip Fakepoint) {
key := a.makeKey(roundTrip.url, roundTrip.method)
delete(a.fakepoints, key)
delete(a.fakepointsCount, key)
}
func (a Agent) makeKey(url, method string) string {
return url + ":" + method
}
func (a Agent) getKey(r http.Request) string {
return r.URL.String() + ":" + r.Method
}