json.go 2.1 KB

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