code: add go.mod and send user list on join

master
ALI Hamza 2019-09-24 10:11:45 +07:00
parent 4eacf3195b
commit d0492bb21f
No known key found for this signature in database
GPG Key ID: BCA8A46C87798C4C
3 changed files with 32 additions and 4 deletions

@ -8,14 +8,16 @@ import (
)
type message struct {
Type string `json:"type"`
Sender string `json:"sender"`
Content string `json:"content"`
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

@ -0,0 +1,5 @@
module gitea.teamortix.com/hamza/go-websockets-talk
go 1.12
require github.com/gorilla/websocket v1.4.1

@ -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=