forked from smallnest/rpcx
/
alias.go
78 lines (67 loc) ยท 1.97 KB
/
alias.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 serverplugin
import (
"context"
"github.com/smallnest/rpcx/protocol"
)
var aliasAppliedKey = "__aliasAppliedKey"
type aliasPair struct {
servicePath, serviceMethod string
}
//AliasPlugin can be used to set aliases for services
type AliasPlugin struct {
Aliases map[string]*aliasPair
ReseverseAliases map[string]*aliasPair
}
// Alias sets a alias for the serviceMethod.
// For example Alias("anewpath&method", "Arith.mul")
func (p *AliasPlugin) Alias(aliasServicePath, aliasServiceMethod string, servicePath, serviceMethod string) {
p.Aliases[aliasServicePath+"."+aliasServiceMethod] = &aliasPair{
servicePath: servicePath,
serviceMethod: serviceMethod,
}
p.ReseverseAliases[servicePath+"."+serviceMethod] = &aliasPair{
servicePath: aliasServicePath,
serviceMethod: aliasServiceMethod,
}
}
// NewAliasPlugin creates a new NewAliasPlugin
func NewAliasPlugin() *AliasPlugin {
return &AliasPlugin{
Aliases: make(map[string]*aliasPair),
ReseverseAliases: make(map[string]*aliasPair),
}
}
// PostReadRequest converts the alias of this service.
func (p *AliasPlugin) PostReadRequest(ctx context.Context, r *protocol.Message, e error) error {
var sp = r.ServicePath
var sm = r.ServiceMethod
k := sp + "." + sm
if p.Aliases != nil {
if pm := p.Aliases[k]; pm != nil {
r.ServicePath = pm.servicePath
r.ServiceMethod = pm.serviceMethod
if r.Metadata == nil {
r.Metadata = make(map[string]string)
}
r.Metadata[aliasAppliedKey] = "true"
}
}
return nil
}
// PreWriteResponse restore servicePath and serviceMethod.
func (p *AliasPlugin) PreWriteResponse(ctx context.Context, r *protocol.Message) error {
if r.Metadata[aliasAppliedKey] != "true" {
return nil
}
var sp = r.ServicePath
var sm = r.ServiceMethod
k := sp + "." + sm
if p.ReseverseAliases != nil {
if pm := p.ReseverseAliases[k]; pm != nil {
r.ServicePath = pm.servicePath
r.ServiceMethod = pm.serviceMethod
delete(r.Metadata, aliasAppliedKey)
}
}
return nil
}