-
Notifications
You must be signed in to change notification settings - Fork 470
/
handler.go
executable file
·84 lines (73 loc) · 2.6 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
79
80
81
82
83
84
package handler
import (
"errors"
"fmt"
"github.com/go-chassis/go-chassis/core/invocation"
"github.com/go-chassis/go-chassis/core/util/string"
)
var errViolateBuildIn = errors.New("can not replace build-in handler func")
//ErrDuplicatedHandler means you registered more than 1 handler with same name
var ErrDuplicatedHandler = errors.New("duplicated handler registration")
var buildIn = []string{BizkeeperConsumer, BizkeeperProvider, Loadbalance, Router, TracingConsumer,
TracingProvider, RatelimiterConsumer, RatelimiterProvider, Transport, FaultInject}
// HandlerFuncMap handler function map
var HandlerFuncMap = make(map[string]func() Handler)
// constant keys for handlers
const (
Transport = "transport"
Loadbalance = "loadbalance"
BizkeeperConsumer = "bizkeeper-consumer"
BizkeeperProvider = "bizkeeper-provider"
TracingConsumer = "tracing-consumer"
TracingProvider = "tracing-provider"
RatelimiterConsumer = "ratelimiter-consumer"
RatelimiterProvider = "ratelimiter-provider"
Router = "router"
FaultInject = "fault-inject"
)
// init is for to initialize the all handlers at boot time
func init() {
//register build-in handler,don't need to call RegisterHandlerFunc
HandlerFuncMap[Transport] = newTransportHandler
HandlerFuncMap[Loadbalance] = newLBHandler
HandlerFuncMap[BizkeeperConsumer] = newBizKeeperConsumerHandler
HandlerFuncMap[BizkeeperProvider] = newBizKeeperProviderHandler
HandlerFuncMap[RatelimiterConsumer] = newConsumerRateLimiterHandler
HandlerFuncMap[RatelimiterProvider] = newProviderRateLimiterHandler
HandlerFuncMap[TracingProvider] = newTracingProviderHandler
HandlerFuncMap[TracingConsumer] = newTracingConsumerHandler
HandlerFuncMap[Router] = newRouterHandler
HandlerFuncMap[FaultInject] = newFaultHandler
}
// Handler interface for handlers
type Handler interface {
// handle invocation transportation,and tr response
Handle(*Chain, *invocation.Invocation, invocation.ResponseCallBack)
Name() string
}
func writeErr(err error, cb invocation.ResponseCallBack) {
r := &invocation.Response{
Err: err,
}
cb(r)
}
// RegisterHandler Let developer custom handler
func RegisterHandler(name string, f func() Handler) error {
if stringutil.StringInSlice(name, buildIn) {
return errViolateBuildIn
}
_, ok := HandlerFuncMap[name]
if ok {
return ErrDuplicatedHandler
}
HandlerFuncMap[name] = f
return nil
}
// CreateHandler create a new handler by name your registered
func CreateHandler(name string) (Handler, error) {
f := HandlerFuncMap[name]
if f == nil {
return nil, fmt.Errorf("don't have handler [%s]", name)
}
return f(), nil
}