Browse Source

Parse message

Volodymyr Tkach 2 years ago
parent
commit
65db35c119
2 changed files with 47 additions and 4 deletions
  1. 1 0
      pubsub/go_reader.go
  2. 46 4
      pubsub/structs.go

+ 1 - 0
pubsub/go_reader.go

@@ -52,6 +52,7 @@ func go_reader(c *Connection) {
 									c.onInfo(fmt.Sprintf("type: %s, data: %#v", answer.Type, answer.Data))
 								}
 							} else {
+								(&answer).Parse()
 								c.onMessage(&answer)
 							}
 						}

+ 46 - 4
pubsub/structs.go

@@ -2,6 +2,7 @@ package pubsub
 
 import (
 	"encoding/json"
+	"fmt"
 )
 
 type AnswerType string
@@ -20,11 +21,38 @@ func (a AnswerType) String() string {
 	return string(a)
 }
 
+// -----------------------------------------------------------------------------
+
 type Answer struct {
-	Type  AnswerType  `json:"type"`
-	Data  interface{} `json:"data,omitempty"`
-	Error string      `json:"error,omitempty"`
-	Nonce string      `json:"nonce,omitempty"`
+	processed bool
+
+	Type  AnswerType `json:"type"`
+	Data  any        `json:"data,omitempty"`
+	Error string     `json:"error,omitempty"`
+	Nonce string     `json:"nonce,omitempty"`
+}
+
+func (a *Answer) Parse() {
+	if a.processed {
+		return
+	}
+	a.processed = true
+
+	data := AnswerDataMessage{}
+
+	switch v := a.Data.(type) {
+	case map[string]any:
+		for fn, fv := range v {
+			if fn == "message" {
+				data.Message = fmt.Sprintf("%s", fv)
+			} else if fn == "topic" {
+				data.Topic = fmt.Sprintf("%s", fv)
+			}
+		}
+	default:
+	}
+
+	a.Data = data
 }
 
 func (a Answer) HasError() bool {
@@ -36,6 +64,20 @@ func (a Answer) JSON() []byte {
 	return bytes
 }
 
+// -----------------------------------------------------------------------------
+
+type AnswerDataMessage struct {
+	Message string `json:"message"`
+	Topic   string `json:"topic"`
+}
+
+func (a AnswerDataMessage) JSON() []byte {
+	bytes, _ := json.Marshal(a)
+	return bytes
+}
+
+// -----------------------------------------------------------------------------
+
 type AnswerDataTopics struct {
 	Topics []string `json:"topics"`
 }