Browse Source

Use structure instead plain text

Volodymyr Tkach 2 years ago
parent
commit
f490d726f5
4 changed files with 28 additions and 7 deletions
  1. 2 3
      pubsub/connection.go
  2. 1 1
      pubsub/go_pinger.go
  3. 1 3
      pubsub/go_reader.go
  4. 24 0
      pubsub/structs.go

+ 2 - 3
pubsub/connection.go

@@ -2,7 +2,6 @@ package pubsub
 
 import (
 	"net/url"
-	"strings"
 	"sync"
 	"time"
 
@@ -118,8 +117,8 @@ func (c *Connection) listenTopis() {
 	for topic := range c.topics {
 		topics = append(topics, topic)
 	}
-	msg := `{"type":"LISTEN","nonce":"","data":{"topics":["` + strings.Join(topics, `","`) + `"]}}`
-	if err := c.Connection.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
+	msg := Response{Type: "LISTEN", Data: DataTopics{Topics: topics}}.JSON()
+	if err := c.Connection.WriteMessage(websocket.TextMessage, msg); err != nil {
 		c.onError(err)
 		c.active = false
 		c.onDisconnect()

+ 1 - 1
pubsub/go_pinger.go

@@ -17,7 +17,7 @@ func go_pinger(c *Connection) {
 					if time.Since(c.ping_start) > TwitchApiPingEach {
 						if err := c.Connection.WriteMessage(
 							websocket.TextMessage,
-							[]byte(`{"type":"PING"}`),
+							Response{Type: "PING"}.JSON(),
 						); err != nil {
 							c.onError(err)
 							c.active = false

+ 1 - 3
pubsub/go_reader.go

@@ -26,9 +26,7 @@ func go_reader(c *Connection) {
 							return
 						}
 					} else {
-						var resp struct {
-							Type string `json:"type"`
-						}
+						var resp Response
 						if err := json.Unmarshal(msg, &resp); err != nil {
 							c.onError(err)
 						} else {

+ 24 - 0
pubsub/structs.go

@@ -0,0 +1,24 @@
+package pubsub
+
+import "encoding/json"
+
+type Response struct {
+	Type  string      `json:"type"`
+	Data  interface{} `json:"data,omitempty"`
+	Error string      `json:"error,omitempty"`
+	Nonce string      `json:"nonce,omitempty"`
+}
+
+func (r Response) JSON() []byte {
+	bytes, _ := json.Marshal(r)
+	return bytes
+}
+
+type DataTopics struct {
+	Topics []string `json:"topics"`
+}
+
+func (d DataTopics) JSON() []byte {
+	bytes, _ := json.Marshal(d)
+	return bytes
+}