json.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package json
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "git.bvbej.com/bvbej/base-golang/pkg/websocket/codec"
  8. )
  9. type jsonCodec struct{}
  10. type jsonReq struct {
  11. Router string `json:"router"`
  12. Data []byte `json:"data"`
  13. Error string `json:"error,omitempty"`
  14. }
  15. type jsonAck struct {
  16. Router string `json:"router"`
  17. Data string `json:"data"`
  18. Error string `json:"error,omitempty"`
  19. }
  20. func (*jsonCodec) Marshal(router string, dataPtr interface{}, retErr error) ([]byte, error) {
  21. if router == "" {
  22. return nil, fmt.Errorf("marshal: router is empty")
  23. }
  24. if dataPtr == nil && retErr == nil {
  25. return nil, fmt.Errorf("marshal data in package is nil. router:%s dt:%T",
  26. router, dataPtr)
  27. }
  28. ack := &jsonAck{
  29. Router: router,
  30. }
  31. if dataPtr != nil {
  32. data, err := json.Marshal(dataPtr)
  33. if err != nil {
  34. return nil, fmt.Errorf("marshal json marshal failed. routerr:%s dt:%T err:%v",
  35. router, dataPtr, err)
  36. }
  37. ack.Data = base64.StdEncoding.EncodeToString(data)
  38. }
  39. if retErr != nil {
  40. ack.Error = retErr.Error()
  41. }
  42. ackByte, err := json.Marshal(ack)
  43. if err != nil {
  44. return nil, fmt.Errorf("marshal json marshal failed. routerr:%s dt:%T err:%v",
  45. router, dataPtr, err)
  46. }
  47. return ackByte, nil
  48. }
  49. func (*jsonCodec) Unmarshal(msg []byte) (int, *codec.MsgPack, error) {
  50. fmt.Sprintln(string(msg))
  51. var l = len(msg)
  52. req := &jsonReq{}
  53. err := json.Unmarshal(msg, req)
  54. if err != nil {
  55. return l, nil, errors.New("unmarshal split message id failed")
  56. }
  57. var router = req.Router
  58. msgPack := &codec.MsgPack{Router: router}
  59. dt := codec.GetMessage(router)
  60. if dt == nil {
  61. return l, nil, fmt.Errorf("unmarshal message not registed. router:%s",
  62. router)
  63. }
  64. if req.Data != nil {
  65. err = json.Unmarshal(req.Data, dt)
  66. if err != nil {
  67. return l, nil, fmt.Errorf("unmarshal json unmarshal failed. dt:%T msg:%s err:%v",
  68. dt, string(msg), err)
  69. }
  70. }
  71. msgPack.DataPtr = dt
  72. if req.Error != "" {
  73. msgPack.Err = errors.New(req.Error)
  74. }
  75. return l, msgPack, nil
  76. }
  77. func (*jsonCodec) ToString(data interface{}) string {
  78. ab, err := json.Marshal(data)
  79. if err != nil {
  80. return fmt.Sprintf("invalid type %T", data)
  81. }
  82. return string(ab)
  83. }
  84. func init() {
  85. codec.RegisterCodec("json_codec", new(jsonCodec))
  86. }