From d0492bb21f2eae49e1e7ae29286a8458b68edc17 Mon Sep 17 00:00:00 2001 From: Hamza Ali Date: Tue, 24 Sep 2019 10:11:45 +0700 Subject: [PATCH] code: add go.mod and send user list on join --- code/hub.go | 29 +++++++++++++++++++++++++---- go.mod | 5 +++++ go.sum | 2 ++ 3 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 go.mod create mode 100644 go.sum diff --git a/code/hub.go b/code/hub.go index dbe5e68..797d64a 100644 --- a/code/hub.go +++ b/code/hub.go @@ -8,14 +8,16 @@ import ( ) type message struct { - Sender string `json:"sender"` - Content string `json:"content"` - Date time.Time `json:"date"` - Success bool `json:"success"` + Type string `json:"type"` + Sender string `json:"sender"` + Content interface{} `json:"content"` + Date time.Time `json:"date"` + Success bool `json:"success"` } func newError(content string) message { return message{ + Type: "error", Sender: "", Content: content, Date: time.Now().UTC(), @@ -25,6 +27,7 @@ func newError(content string) message { func newMessage(sender string, content string) message { return message{ + Type: "message", Sender: sender, Content: content, Date: time.Now().UTC(), @@ -40,6 +43,23 @@ func (m message) dispatch() { var usernames = make(map[*websocket.Conn]string) +func sendUserList(who *websocket.Conn) { + list := []string{} + for _, username := range usernames { + list = append(list, username) + } + + m := message{ + Type: "users", + Sender: "", + Content: list, + Date: time.Now().UTC(), + Success: true, + } + + _ = who.WriteJSON(m) +} + func sendChatMessage(sender *websocket.Conn, msg string) { m := newMessage(usernames[sender], msg) m.dispatch() @@ -61,6 +81,7 @@ func handleIncomingMessage(sender *websocket.Conn, msg string) { usernames[sender] = username + sendUserList(sender) m := newMessage("server", username+" has joined the chat") m.dispatch() return diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..30f695c --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module gitea.teamortix.com/hamza/go-websockets-talk + +go 1.12 + +require github.com/gorilla/websocket v1.4.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1f9b923 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=