-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
78 lines (67 loc) · 1.4 KB
/
handler.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
package httpclient
import (
"errors"
"httpclient/circuitbreaker"
)
type HandlerFunc func(*Builder)
func GetOriginHttpHandler() HandlerFunc {
return func(b *Builder) {
resp, err := b.client.client.Do(b.request)
b.response = resp
b.SetError(err)
}
}
func GetBreakerHandler() HandlerFunc {
return func(b *Builder) {
if b.conf.DisableBreaker {
b.next()
return
}
breaker, err := b.GetUrlBreaker(b.url)
if err != nil {
b.SetError(err)
return
}
state, err := breaker.Call(b.GetContext(), func() error {
b.next()
return b.GetError()
}, 0)
if state == circuitbreaker.BreakerNotReady && b.GetDegradedResponse() != nil {
b.response = b.GetDegradedResponse()
b.SetError(errors.New("断路器已降级"))
} else if err != nil {
b.SetError(err)
}
}
}
func GetFilterHandler() HandlerFunc {
return func(b *Builder) {
b.next()
filterFunc := b.GetFilterFunc()
if filterFunc != nil {
err := filterFunc(b.request, b.response)
b.SetError(err)
} else {
GetAccessStatusCodeHandler()(b)
}
}
}
func GetAccessStatusCodeHandler() HandlerFunc {
return func(b *Builder) {
b.next()
resp := b.response
if resp == nil {
return
}
isAccess := len(b.GetAccessCode()) == 0
for _, code := range b.GetAccessCode() {
if resp.StatusCode == code {
isAccess = true
break
}
}
if !isAccess {
b.SetError(errors.New("wrong status code"))
}
}
}