forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codecreg.go
61 lines (49 loc) · 1.18 KB
/
codecreg.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
package codec
import (
"fmt"
"github.com/davyxu/cellnet"
)
var registedCodecs []cellnet.Codec
// 注册编码器
func RegisterCodec(c cellnet.Codec) {
if GetCodec(c.Name()) != nil {
panic("duplicate codec: " + c.Name())
}
registedCodecs = append(registedCodecs, c)
}
// 获取编码器
func GetCodec(name string) cellnet.Codec {
for _, c := range registedCodecs {
if c.Name() == name {
return c
}
}
return nil
}
// cellnet自带的编码对应包
func getPackageByCodecName(name string) string {
switch name {
case "binary":
return "github.com/davyxu/cellnet/codec/binary"
case "gogopb":
return "github.com/davyxu/cellnet/codec/gogopb"
case "httpjson":
return "github.com/davyxu/cellnet/codec/httpjson"
case "json":
return "github.com/davyxu/cellnet/codec/json"
case "protoplus":
return "github.com/davyxu/cellnet/codec/protoplus"
default:
return "package/to/your/codec"
}
}
// 指定编码器不存在时,报错
func MustGetCodec(name string) cellnet.Codec {
codec := GetCodec(name)
if codec == nil {
panic(fmt.Sprintf("codec not found '%s'\ntry to add code below:\nimport (\n _ \"%s\"\n)\n\n",
name,
getPackageByCodecName(name)))
}
return codec
}