2019-09-23 12:18:00 +07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
type message struct {
|
|
|
|
Sender string `json:"sender"`
|
|
|
|
Content string `json:"content"`
|
|
|
|
Date time.Time `json:"date"`
|
2019-09-23 23:23:21 +07:00
|
|
|
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,
|
|
|
|
}
|
2019-09-23 12:18:00 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m message) dispatch() {
|
2019-09-23 23:23:21 +07:00
|
|
|
for client := range usernames {
|
|
|
|
_ = client.WriteJSON(m)
|
2019-09-23 12:18:00 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-23 23:23:21 +07:00
|
|
|
var usernames = make(map[*websocket.Conn]string)
|
2019-09-23 12:18:00 +07:00
|
|
|
|
|
|
|
func sendChatMessage(sender *websocket.Conn, msg string) {
|
2019-09-23 23:23:21 +07:00
|
|
|
m := newMessage(usernames[sender], msg)
|
2019-09-23 12:18:00 +07:00
|
|
|
m.dispatch()
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleDisconnection(sender *websocket.Conn) {
|
2019-09-23 23:23:21 +07:00
|
|
|
m := newMessage("server", usernames[sender]+" has left the chat.")
|
2019-09-23 12:18:00 +07:00
|
|
|
m.dispatch()
|
2019-09-23 23:23:21 +07:00
|
|
|
delete(usernames, sender)
|
2019-09-23 12:18:00 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
func handleIncomingMessage(sender *websocket.Conn, msg string) {
|
2019-09-23 23:23:21 +07:00
|
|
|
if _, ok := usernames[sender]; !ok {
|
|
|
|
username := strings.TrimSpace(msg)
|
|
|
|
if username == "" || username == "server" {
|
|
|
|
sender.WriteJSON(newError("You have an illegal nickname"))
|
|
|
|
return
|
2019-09-23 12:18:00 +07:00
|
|
|
}
|
2019-09-23 23:23:21 +07:00
|
|
|
|
|
|
|
usernames[sender] = username
|
|
|
|
|
|
|
|
m := newMessage("server", username+" has joined the chat")
|
2019-09-23 12:18:00 +07:00
|
|
|
m.dispatch()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
sendChatMessage(sender, msg)
|
|
|
|
}
|