|
|
@ -8,14 +8,16 @@ import (
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
type message struct {
|
|
|
|
type message struct {
|
|
|
|
Sender string `json:"sender"`
|
|
|
|
Type string `json:"type"`
|
|
|
|
Content string `json:"content"`
|
|
|
|
Sender string `json:"sender"`
|
|
|
|
Date time.Time `json:"date"`
|
|
|
|
Content interface{} `json:"content"`
|
|
|
|
Success bool `json:"success"`
|
|
|
|
Date time.Time `json:"date"`
|
|
|
|
|
|
|
|
Success bool `json:"success"`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func newError(content string) message {
|
|
|
|
func newError(content string) message {
|
|
|
|
return message{
|
|
|
|
return message{
|
|
|
|
|
|
|
|
Type: "error",
|
|
|
|
Sender: "",
|
|
|
|
Sender: "",
|
|
|
|
Content: content,
|
|
|
|
Content: content,
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
Date: time.Now().UTC(),
|
|
|
@ -25,6 +27,7 @@ func newError(content string) message {
|
|
|
|
|
|
|
|
|
|
|
|
func newMessage(sender string, content string) message {
|
|
|
|
func newMessage(sender string, content string) message {
|
|
|
|
return message{
|
|
|
|
return message{
|
|
|
|
|
|
|
|
Type: "message",
|
|
|
|
Sender: sender,
|
|
|
|
Sender: sender,
|
|
|
|
Content: content,
|
|
|
|
Content: content,
|
|
|
|
Date: time.Now().UTC(),
|
|
|
|
Date: time.Now().UTC(),
|
|
|
@ -40,6 +43,23 @@ func (m message) dispatch() {
|
|
|
|
|
|
|
|
|
|
|
|
var usernames = make(map[*websocket.Conn]string)
|
|
|
|
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) {
|
|
|
|
func sendChatMessage(sender *websocket.Conn, msg string) {
|
|
|
|
m := newMessage(usernames[sender], msg)
|
|
|
|
m := newMessage(usernames[sender], msg)
|
|
|
|
m.dispatch()
|
|
|
|
m.dispatch()
|
|
|
@ -61,6 +81,7 @@ func handleIncomingMessage(sender *websocket.Conn, msg string) {
|
|
|
|
|
|
|
|
|
|
|
|
usernames[sender] = username
|
|
|
|
usernames[sender] = username
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
sendUserList(sender)
|
|
|
|
m := newMessage("server", username+" has joined the chat")
|
|
|
|
m := newMessage("server", username+" has joined the chat")
|
|
|
|
m.dispatch()
|
|
|
|
m.dispatch()
|
|
|
|
return
|
|
|
|
return
|
|
|
|