all clients should be saved in cache
This commit is contained in:
+59
-11
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -20,25 +21,72 @@ func ServeConnection(responseWriter http.ResponseWriter, request *http.Request)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
|
||||
defer cancel()
|
||||
|
||||
for {
|
||||
var clientMessage any
|
||||
var (
|
||||
isAuthenticated = false
|
||||
continueConnection = true
|
||||
client = Client{}
|
||||
)
|
||||
|
||||
for continueConnection {
|
||||
var clientMessage map[string]any
|
||||
err := wsjson.Read(ctx, connection, &clientMessage)
|
||||
if err != nil {
|
||||
log.Printf("read error: %clientMessage", err)
|
||||
return
|
||||
}
|
||||
log.Printf("received: %clientMessage", clientMessage)
|
||||
|
||||
// process and optionally respond
|
||||
err = wsjson.Write(ctx, connection, map[string]string{"status": "ok"})
|
||||
if err != nil {
|
||||
log.Printf("write error: %clientMessage", err)
|
||||
return
|
||||
if len(clientMessage) > 0 {
|
||||
if isAuthenticated {
|
||||
handleAuthenticatedMessage()
|
||||
} else {
|
||||
handleUnauthenticatedMessage(connection, &client, &clientMessage, &isAuthenticated, &continueConnection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleUnauthenticatedMessage() {
|
||||
|
||||
func sendMessageCloseIfTimeout(conn *websocket.Conn, message *map[string]any) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
|
||||
defer cancel()
|
||||
|
||||
err := wsjson.Write(ctx, conn, message)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
closeConnection(conn)
|
||||
}
|
||||
log.Printf("write error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func handleUnauthenticatedMessage(conn *websocket.Conn, client *Client, message *map[string]any, isAuthenticated *bool, continueConnection *bool) {
|
||||
token, ok := (*message)["token"].(string)
|
||||
if !ok {
|
||||
var errmsg = map[string]any{
|
||||
"type": WSServerResponse(BadMessage),
|
||||
"message": "token required",
|
||||
}
|
||||
sendMessageCloseIfTimeout(conn, &errmsg)
|
||||
return
|
||||
}
|
||||
|
||||
err := SetClientFromToken(client, token)
|
||||
if err != nil {
|
||||
var errmsg = map[string]any{
|
||||
"type": WSServerResponse(InvalidCredentials),
|
||||
"message": "bad token",
|
||||
}
|
||||
sendMessageCloseIfTimeout(conn, &errmsg)
|
||||
continueConnection = false
|
||||
return
|
||||
}
|
||||
isAuthenticated = true
|
||||
clientInCache, ok := ClientsMap[]
|
||||
}
|
||||
|
||||
func handleAuthenticatedMessage() {
|
||||
|
||||
}
|
||||
|
||||
func closeConnection(conn *websocket.Conn) {
|
||||
conn.Close(websocket.StatusNormalClosure, "closing connection")
|
||||
}
|
||||
func handleAuthenticatedMessage() {}
|
||||
|
||||
Reference in New Issue
Block a user