From 3d20edd96081d4537ac47660df12b76a649102d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ken-H=C3=A5vard=20Lieng?= Date: Sun, 7 Jun 2015 06:32:19 +0200 Subject: [PATCH] Move JSON encoding to conn.send() --- server/conn.go | 8 ++++---- server/json_types.go | 4 ++-- server/session.go | 11 +++-------- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/server/conn.go b/server/conn.go index 38ee3a83..699898a2 100644 --- a/server/conn.go +++ b/server/conn.go @@ -9,14 +9,14 @@ import ( type conn struct { conn *websocket.Conn in chan WSRequest - out chan []byte + out chan WSResponse } func newConn(ws *websocket.Conn) *conn { return &conn{ conn: ws, in: make(chan WSRequest, 32), - out: make(chan []byte, 32), + out: make(chan WSResponse, 32), } } @@ -26,12 +26,12 @@ func (c *conn) send() { for { select { - case msg, ok := <-c.out: + case res, ok := <-c.out: if !ok { return } - err = c.conn.WriteMessage(websocket.TextMessage, msg) + err = c.conn.WriteJSON(res) case <-ping: err = c.conn.WriteJSON(WSResponse{Type: "ping"}) diff --git a/server/json_types.go b/server/json_types.go index a8a78bc7..dac57955 100644 --- a/server/json_types.go +++ b/server/json_types.go @@ -12,8 +12,8 @@ type WSRequest struct { } type WSResponse struct { - Type string `json:"type"` - Response *json.RawMessage `json:"response"` + Type string `json:"type"` + Response interface{} `json:"response"` } type Connect struct { diff --git a/server/session.go b/server/session.go index c412aea2..6ef561de 100644 --- a/server/session.go +++ b/server/session.go @@ -1,7 +1,6 @@ package server import ( - "encoding/json" "sync" "github.com/khlieng/name_pending/irc" @@ -14,7 +13,7 @@ type Session struct { ws map[string]*conn wsLock sync.Mutex - out chan []byte + out chan WSResponse user *storage.User } @@ -23,7 +22,7 @@ func NewSession() *Session { return &Session{ irc: make(map[string]*irc.Client), ws: make(map[string]*conn), - out: make(chan []byte, 32), + out: make(chan WSResponse, 32), } } @@ -68,11 +67,7 @@ func (s *Session) deleteWS(addr string) { } func (s *Session) sendJSON(t string, v interface{}) { - data, _ := json.Marshal(v) - raw := json.RawMessage(data) - res, _ := json.Marshal(WSResponse{Type: t, Response: &raw}) - - s.out <- res + s.out <- WSResponse{t, v} } func (s *Session) sendError(err error, server string) {