github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/common/msgparser/mux_handler.go (about) 1 package msgparser 2 3 import ( 4 message2 "github.com/nyan233/littlerpc/core/protocol/message" 5 mux2 "github.com/nyan233/littlerpc/core/protocol/message/mux" 6 ) 7 8 type muxHandler struct { 9 } 10 11 func (m *muxHandler) Header() []byte { 12 return []byte{mux2.Enabled} 13 } 14 15 func (m *muxHandler) BaseLen() (BaseLenType, int) { 16 return MultiRequest, mux2.BlockBaseLen 17 } 18 19 func (m *muxHandler) MessageLength(base []byte) int { 20 var muxBlock mux2.Block 21 err := mux2.Unmarshal(base, &muxBlock) 22 if err != nil { 23 return -1 24 } 25 // +BaseLen的原因是MuxBlock.PayloadLength并非是全量的长度 26 // PayloadLength仅仅是载荷的大小, 为了Parser能够正确识别游标 27 _, baseLen := m.BaseLen() 28 return int(muxBlock.PayloadLength) + baseLen 29 } 30 31 func (m *muxHandler) Unmarshal(data []byte, msg *message2.Message) (Action, error) { 32 var muxBlock mux2.Block 33 if err := mux2.Unmarshal(data, &muxBlock); err != nil { 34 return -1, err 35 } 36 err := message2.UnmarshalFromMux(muxBlock.Payloads, msg) 37 if err != nil { 38 return -1, err 39 } 40 if uint32(muxBlock.PayloadLength) >= msg.GetAndSetLength() { 41 // 读出完整的消息 42 err := message2.Unmarshal(muxBlock.Payloads, msg) 43 if err != nil { 44 return -1, err 45 } 46 return UnmarshalComplete, nil 47 } 48 return UnmarshalBase, nil 49 }