code/server: use the type string in the message struct to specify message/error/join/leave

master
ALI Hamza 2019-09-25 16:02:51 +07:00
parent 9f8799bfff
commit 803f64c0d8
No known key found for this signature in database
GPG Key ID: BCA8A46C87798C4C
1 changed files with 5 additions and 5 deletions

@ -25,9 +25,9 @@ func newError(content string) message {
} }
} }
func newMessage(sender string, content string) message { func newMessage(msgType string, sender string, content string) message {
return message{ return message{
Type: "message", Type: msgType,
Sender: sender, Sender: sender,
Content: content, Content: content,
Date: time.Now().UTC(), Date: time.Now().UTC(),
@ -61,12 +61,12 @@ func sendUserList(who *websocket.Conn) {
} }
func sendChatMessage(sender *websocket.Conn, msg string) { func sendChatMessage(sender *websocket.Conn, msg string) {
m := newMessage(usernames[sender], msg) m := newMessage("message", usernames[sender], msg)
m.dispatch() m.dispatch()
} }
func handleDisconnection(sender *websocket.Conn) { func handleDisconnection(sender *websocket.Conn) {
m := newMessage("server", usernames[sender]+" has left the chat.") m := newMessage("leave", "server", usernames[sender])
m.dispatch() m.dispatch()
delete(usernames, sender) delete(usernames, sender)
} }
@ -81,7 +81,7 @@ func handleIncomingMessage(sender *websocket.Conn, msg string) {
sendUserList(sender) sendUserList(sender)
usernames[sender] = username usernames[sender] = username
m := newMessage("server", username+" has joined the chat") m := newMessage("join", "server", username)
m.dispatch() m.dispatch()
return return
} }