structs.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package pubsub
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type AnswerType string
  7. const (
  8. Listen AnswerType = "LISTEN"
  9. Message AnswerType = "MESSAGE"
  10. Ping AnswerType = "PING"
  11. Pong AnswerType = "PONG"
  12. Reconnect AnswerType = "RECONNECT"
  13. Response AnswerType = "RESPONSE"
  14. Unlisten AnswerType = "UNLISTEN"
  15. )
  16. func (a AnswerType) String() string {
  17. return string(a)
  18. }
  19. // -----------------------------------------------------------------------------
  20. type Answer struct {
  21. processed bool
  22. Type AnswerType `json:"type"`
  23. Data any `json:"data,omitempty"`
  24. Error string `json:"error,omitempty"`
  25. Nonce string `json:"nonce,omitempty"`
  26. }
  27. func (a *Answer) Parse() {
  28. if a.processed {
  29. return
  30. }
  31. a.processed = true
  32. data := AnswerDataMessage{}
  33. switch v := a.Data.(type) {
  34. case map[string]any:
  35. for fn, fv := range v {
  36. if fn == "message" {
  37. data.Message = fmt.Sprintf("%s", fv)
  38. } else if fn == "topic" {
  39. data.Topic = fmt.Sprintf("%s", fv)
  40. }
  41. }
  42. default:
  43. }
  44. a.Data = data
  45. }
  46. func (a *Answer) GetData() AnswerDataMessage {
  47. switch v := a.Data.(type) {
  48. case AnswerDataMessage:
  49. return v
  50. default:
  51. return AnswerDataMessage{}
  52. }
  53. }
  54. func (a Answer) HasError() bool {
  55. return a.Error != ""
  56. }
  57. func (a Answer) JSON() []byte {
  58. bytes, _ := json.Marshal(a)
  59. return bytes
  60. }
  61. // -----------------------------------------------------------------------------
  62. type AnswerDataMessage struct {
  63. Message string `json:"message"`
  64. Topic string `json:"topic"`
  65. }
  66. func (a AnswerDataMessage) JSON() []byte {
  67. bytes, _ := json.Marshal(a)
  68. return bytes
  69. }
  70. // -----------------------------------------------------------------------------
  71. type AnswerDataTopics struct {
  72. Topics []string `json:"topics"`
  73. }
  74. func (a AnswerDataTopics) JSON() []byte {
  75. bytes, _ := json.Marshal(a)
  76. return bytes
  77. }