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