github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/common/msgparser/msghandler.go (about) 1 package msgparser 2 3 import ( 4 "github.com/nyan233/littlerpc/core/middle/codec" 5 "github.com/nyan233/littlerpc/core/protocol/message" 6 "math" 7 ) 8 9 var handlerCollect [math.MaxUint8 + 1]MessageHandler 10 11 type Action int 12 type BaseLenType int 13 14 const ( 15 UnmarshalBase Action = 0x34 // 已经序列化基本信息, 但是还够不成一个完整的消息, 需要将消息提升到noReadyBuffer中 16 UnmarshalComplete Action = 0x45 // 序列化完整消息完成 17 18 // SingleRequest 数据在单次请求中被传完, 适合HTTP之类的协议, LMessageParser在遇到 19 // 这个选项时会直接之间使用ParseMsg()传入的bytes来触发Unmarshal() 20 // TCP之类的协议使用这个选项会引发半包之类的问题 21 SingleRequest BaseLenType = 0x65 22 // MultiRequest 数据在可能在多次请求中被传完, 适合TCP之类的协议 23 MultiRequest BaseLenType = 0x76 24 ) 25 26 type MessageHandler interface { 27 Header() []byte 28 BaseLen() (BaseLenType, int) 29 MessageLength(base []byte) int 30 Unmarshal(data []byte, msg *message.Message) (Action, error) 31 } 32 33 func RegisterHandler(handler MessageHandler) { 34 if handler == nil { 35 panic("handler is empty") 36 } 37 headers := handler.Header() 38 if len(headers) == 0 { 39 panic("header not found") 40 } 41 for _, header := range headers { 42 handlerCollect[header] = handler 43 } 44 } 45 46 func GetHandler(magicNumber uint8) MessageHandler { 47 return handlerCollect[magicNumber] 48 } 49 50 func init() { 51 RegisterHandler(&noMuxHandler{}) 52 RegisterHandler(&muxHandler{}) 53 RegisterHandler(&jsonRpc2Handler{Codec: codec.Get("json")}) 54 }