pack.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2018 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package json
  15. import (
  16. "bytes"
  17. "encoding/binary"
  18. "encoding/json"
  19. "reflect"
  20. )
  21. func (msgCtl *MsgCtl) unpack(typeByte byte, buffer []byte, msgIn Message) (msg Message, err error) {
  22. if msgIn == nil {
  23. t, ok := msgCtl.typeMap[typeByte]
  24. if !ok {
  25. err = ErrMsgType
  26. return
  27. }
  28. msg = reflect.New(t).Interface().(Message)
  29. } else {
  30. msg = msgIn
  31. }
  32. err = json.Unmarshal(buffer, &msg)
  33. return
  34. }
  35. func (msgCtl *MsgCtl) UnPackInto(buffer []byte, msg Message) (err error) {
  36. _, err = msgCtl.unpack(' ', buffer, msg)
  37. return
  38. }
  39. func (msgCtl *MsgCtl) UnPack(typeByte byte, buffer []byte) (msg Message, err error) {
  40. return msgCtl.unpack(typeByte, buffer, nil)
  41. }
  42. func (msgCtl *MsgCtl) Pack(msg Message) ([]byte, error) {
  43. typeByte, ok := msgCtl.typeByteMap[reflect.TypeOf(msg).Elem()]
  44. if !ok {
  45. return nil, ErrMsgType
  46. }
  47. content, err := json.Marshal(msg)
  48. if err != nil {
  49. return nil, err
  50. }
  51. buffer := bytes.NewBuffer(nil)
  52. buffer.WriteByte(typeByte)
  53. binary.Write(buffer, binary.BigEndian, int64(len(content)))
  54. buffer.Write(content)
  55. return buffer.Bytes(), nil
  56. }