code: refactor variable names and remove unnecessary logs

master
ALI Hamza 2019-09-24 06:23:21 +07:00
parent c2bb0098db
commit 4eacf3195b
No known key found for this signature in database
GPG Key ID: 7C608266BF384ADC
3 changed files with 45 additions and 30 deletions

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

@ -2,7 +2,6 @@ package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
@ -18,22 +17,16 @@ var (
func websocketConnection(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Fprintf(w, "Internal server error: %s", err)
fmt.Printf("Internal server error: %s", err)
_, _ = fmt.Fprint(w, "You must use the web socket protocol to connect to this endpoint.", err)
return
}
defer ws.Close()
ws.WriteMessage(websocket.TextMessage, []byte("nickname"))
for {
_, p, err := ws.ReadMessage()
if err != nil {
handleDisconnection(ws)
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}

@ -1 +1,10 @@
<p>sawp</p>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Go Chat Application</title>
</head>
<body>
</body>
</html>