json.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 init() {
  21. codec.RegisterCodec("json_codec", new(jsonCodec))
  22. }
  23. func (*jsonCodec) Marshal(router string, dataPtr any, retErr error) ([]byte, error) {
  24. if router == "" {
  25. return nil, fmt.Errorf("marshal: router is empty")
  26. }
  27. if dataPtr == nil && retErr == nil {
  28. return nil, fmt.Errorf("marshal data in package is nil. router:%s dt:%T",
  29. router, dataPtr)
  30. }
  31. ack := &jsonAck{
  32. Router: router,
  33. }
  34. if dataPtr != nil {
  35. data, err := json.Marshal(dataPtr)
  36. if err != nil {
  37. return nil, fmt.Errorf("marshal json marshal failed. routerr:%s dt:%T err:%v",
  38. router, dataPtr, err)
  39. }
  40. ack.Data = base64.StdEncoding.EncodeToString(data)
  41. }
  42. if retErr != nil {
  43. ack.Error = retErr.Error()
  44. }
  45. ackByte, err := json.Marshal(ack)
  46. if err != nil {
  47. return nil, fmt.Errorf("marshal json marshal failed. routerr:%s dt:%T err:%v",
  48. router, dataPtr, err)
  49. }
  50. return ackByte, nil
  51. }
  52. func (*jsonCodec) Unmarshal(msg []byte) (int, *codec.MsgPack, error) {
  53. fmt.Sprintln(string(msg))
  54. var l = len(msg)
  55. req := &jsonReq{}
  56. err := json.Unmarshal(msg, req)
  57. if err != nil {
  58. return l, nil, errors.New("unmarshal split message id failed")
  59. }
  60. var router = req.Router
  61. msgPack := &codec.MsgPack{Router: router}
  62. dt := codec.GetMessage(router)
  63. if dt == nil {
  64. return l, nil, fmt.Errorf("unmarshal message not registed. router:%s",
  65. router)
  66. }
  67. if req.Data != nil {
  68. err = json.Unmarshal(req.Data, dt)
  69. if err != nil {
  70. return l, nil, fmt.Errorf("unmarshal json unmarshal failed. dt:%T msg:%s err:%v",
  71. dt, string(msg), err)
  72. }
  73. }
  74. msgPack.DataPtr = dt
  75. if req.Error != "" {
  76. msgPack.Err = errors.New(req.Error)
  77. }
  78. return l, msgPack, nil
  79. }
  80. func (*jsonCodec) ToString(data any) string {
  81. ab, err := json.Marshal(data)
  82. if err != nil {
  83. return fmt.Sprintf("invalid type %T", data)
  84. }
  85. return string(ab)
  86. }