all clients should be saved in cache

This commit is contained in:
2026-03-16 18:02:32 +01:00
parent 66e189d247
commit bbd3d390c2
7 changed files with 150 additions and 33 deletions
+59 -11
View File
@@ -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() {}