|
|
|
@ -11,44 +11,57 @@ type message struct {
|
|
|
|
|
Sender string `json:"sender"`
|
|
|
|
|
Content string `json:"content"`
|
|
|
|
|
Date time.Time `json:"date"`
|
|
|
|
|
Success bool `json:"success"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newError(content string) message {
|
|
|
|
|
return message{
|
|
|
|
|
Sender: "",
|
|
|
|
|
Content: content,
|
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
|
Success: false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newMessage(sender string, content string) message {
|
|
|
|
|
return message{
|
|
|
|
|
Sender: sender,
|
|
|
|
|
Content: content,
|
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
|
Success: true,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (m message) dispatch() {
|
|
|
|
|
for client := range connections {
|
|
|
|
|
client.WriteJSON(m)
|
|
|
|
|
for client := range usernames {
|
|
|
|
|
_ = client.WriteJSON(m)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var connections = make(map[*websocket.Conn]string)
|
|
|
|
|
var usernames = make(map[*websocket.Conn]string)
|
|
|
|
|
|
|
|
|
|
func sendChatMessage(sender *websocket.Conn, msg string) {
|
|
|
|
|
m := message{
|
|
|
|
|
Sender: connections[sender],
|
|
|
|
|
Content: msg,
|
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
|
}
|
|
|
|
|
m := newMessage(usernames[sender], msg)
|
|
|
|
|
m.dispatch()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func handleDisconnection(sender *websocket.Conn) {
|
|
|
|
|
m := message{
|
|
|
|
|
Sender: "server",
|
|
|
|
|
Content: connections[sender] + " has left the chat",
|
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
|
}
|
|
|
|
|
m := newMessage("server", usernames[sender]+" has left the chat.")
|
|
|
|
|
m.dispatch()
|
|
|
|
|
delete(connections, sender)
|
|
|
|
|
delete(usernames, sender)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func handleIncomingMessage(sender *websocket.Conn, msg string) {
|
|
|
|
|
if _, ok := connections[sender]; !ok {
|
|
|
|
|
connections[sender] = strings.TrimSpace(msg)
|
|
|
|
|
|
|
|
|
|
m := message{
|
|
|
|
|
Sender: "server",
|
|
|
|
|
Content: msg + " has joined the chat",
|
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
|
if _, ok := usernames[sender]; !ok {
|
|
|
|
|
username := strings.TrimSpace(msg)
|
|
|
|
|
if username == "" || username == "server" {
|
|
|
|
|
sender.WriteJSON(newError("You have an illegal nickname"))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
usernames[sender] = username
|
|
|
|
|
|
|
|
|
|
m := newMessage("server", username+" has joined the chat")
|
|
|
|
|
m.dispatch()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|