golang-im聊天
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

76 lines
1.7 KiB

  1. package util
  2. import (
  3. "encoding/json"
  4. "gim/pkg/logger"
  5. "gim/pkg/pb"
  6. jsoniter "github.com/json-iterator/go"
  7. "google.golang.org/protobuf/proto"
  8. "go.uber.org/zap"
  9. )
  10. func JsonMarshal(v interface{}) string {
  11. bytes, err := json.Marshal(v)
  12. if err != nil {
  13. logger.Logger.Error("json序列化:", zap.Error(err))
  14. }
  15. return Bytes2str(bytes)
  16. }
  17. func FormatMessage(messageType pb.MessageType, messageContent []byte) string {
  18. if messageType == pb.MessageType_MT_UNKNOWN {
  19. logger.Logger.Error("error message type")
  20. return "error message type"
  21. }
  22. var (
  23. msg proto.Message
  24. err error
  25. )
  26. switch messageType {
  27. case pb.MessageType_MT_TEXT:
  28. msg = &pb.Text{}
  29. err = proto.Unmarshal(messageContent, msg)
  30. case pb.MessageType_MT_FACE:
  31. msg = &pb.Text{}
  32. err = proto.Unmarshal(messageContent, msg)
  33. case pb.MessageType_MT_VOICE:
  34. msg = &pb.Text{}
  35. err = proto.Unmarshal(messageContent, msg)
  36. case pb.MessageType_MT_IMAGE:
  37. msg = &pb.Text{}
  38. err = proto.Unmarshal(messageContent, msg)
  39. case pb.MessageType_MT_FILE:
  40. msg = &pb.Text{}
  41. err = proto.Unmarshal(messageContent, msg)
  42. case pb.MessageType_MT_LOCATION:
  43. msg = &pb.Text{}
  44. err = proto.Unmarshal(messageContent, msg)
  45. case pb.MessageType_MT_COMMAND:
  46. msgCmd := &pb.Command{
  47. Code: 0,
  48. Data: nil,
  49. }
  50. err = proto.Unmarshal(messageContent, msgCmd)
  51. if msgCmd.Code == int32(pb.PushCode_PC_ADD_FRIEND) {
  52. msg = &pb.AddFriendPush{}
  53. err = proto.Unmarshal(messageContent, msg)
  54. }
  55. case pb.MessageType_MT_CUSTOM:
  56. msg = &pb.Text{}
  57. err = proto.Unmarshal(messageContent, msg)
  58. }
  59. if err != nil {
  60. logger.Sugar.Error(err)
  61. return ""
  62. }
  63. bytes, err := jsoniter.Marshal(msg)
  64. if err != nil {
  65. logger.Sugar.Error(err)
  66. return ""
  67. }
  68. return Bytes2str(bytes)
  69. }