[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"academy-blogs-en-1-1-all-golang-websocket-connection-management-all--*":3,"academy-blog-translations-bebwb61pxsyy11j":74},{"data":4,"page":62,"perPage":62,"totalItems":62,"totalPages":62},[5],{"alt":6,"collectionId":7,"collectionName":8,"content":9,"cover_image":10,"cover_image_path":11,"created":12,"created_by":13,"expand":14,"id":68,"keywords":69,"locale":44,"published_at":70,"scheduled_at":13,"school_blog":66,"short_description":71,"slug":72,"status":64,"title":6,"updated":73,"updated_by":13,"views":67},"EP.80 Building Connection Management for WebSocket Chat","sclblg987654321","school_blog_translations","\u003Cp>In a real-time WebSocket chat application with multiple concurrent users, Connection Management is one of the most critical components. Without proper connection handling, you could encounter serious issues such as:\u003C\u002Fp>\u003Cul>\u003Cli>Messages sent to the wrong user\u003C\u002Fli>\u003Cli>Unreleased memory due to connection leaks\u003C\u002Fli>\u003Cli>System crashes when handling too many users\u003C\u002Fli>\u003C\u002Ful>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔸 Why Connection Management Matters\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>✅ Track connected users\u003Cbr>Know who’s currently connected and possibly which device they're using.\u003C\u002Fp>\u003Cp>✅ Deliver messages correctly\u003Cbr>The system must know the exact WebSocket connection associated with each user to ensure correct message delivery.\u003C\u002Fp>\u003Cp>✅ Detect disconnections\u003Cbr>Handle timeouts, browser closures, or unstable internet connections.\u003C\u002Fp>\u003Cp>✅ Improve system stability\u003Cbr>Prevent memory leaks and ensure scalability for high user volumes.\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔸 A Good Connection Management Architecture Should Include:\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cul>\u003Cli>Connection Hub \u002F Pool:\u003Cbr>A centralized place to store all active connections.\u003C\u002Fli>\u003Cli>User ↔ Connection Mapping:\u003Cbr>Mapping between \u003Ccode inline=\"\">userID\u003C\u002Fcode> and connection to allow targeted messaging.\u003C\u002Fli>\u003Cli>Broadcast &amp; Private Messaging Support:\u003Cbr>Send messages to all users or a specific user.\u003C\u002Fli>\u003C\u002Ful>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>✅ Sample Golang Code: Simple Connection Management System\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">package main\n\nimport (\n    \"sync\"\n    \"github.com\u002Fgorilla\u002Fwebsocket\"\n    \"fmt\"\n)\n\n\u002F\u002F Represents each user's WebSocket connection\ntype Connection struct {\n    ws   *websocket.Conn\n    user string\n}\n\n\u002F\u002F Hub keeps track of all connections\ntype Hub struct {\n    connections map[string]*Connection \u002F\u002F key: userID\n    lock        sync.RWMutex\n}\n\n\u002F\u002F Create a new Hub\nfunc NewHub() *Hub {\n    return &amp;Hub{\n        connections: make(map[string]*Connection),\n    }\n}\n\n\u002F\u002F ✅ Add a new connection\nfunc (h *Hub) AddConnection(userID string, conn *websocket.Conn) {\n    h.lock.Lock()\n    defer h.lock.Unlock()\n\n    h.connections[userID] = &amp;Connection{\n        ws:   conn,\n        user: userID,\n    }\n\n    fmt.Printf(\"[+] %s connected\\n\", userID)\n}\n\n\u002F\u002F ✅ Remove connection on disconnect\nfunc (h *Hub) RemoveConnection(userID string) {\n    h.lock.Lock()\n    defer h.lock.Unlock()\n\n    if conn, ok := h.connections[userID]; ok {\n        conn.ws.Close()\n        delete(h.connections, userID)\n        fmt.Printf(\"[-] %s disconnected\\n\", userID)\n    }\n}\n\n\u002F\u002F ✅ Send private message to specific user\nfunc (h *Hub) SendToUser(userID string, message string) {\n    h.lock.RLock()\n    defer h.lock.RUnlock()\n\n    if conn, ok := h.connections[userID]; ok {\n        err := conn.ws.WriteMessage(websocket.TextMessage, []byte(message))\n        if err != nil {\n            fmt.Println(\"[x] Send to\", userID, \"failed:\", err)\n        }\n    }\n}\n\n\u002F\u002F ✅ Broadcast message to all users\nfunc (h *Hub) Broadcast(message string) {\n    h.lock.RLock()\n    defer h.lock.RUnlock()\n\n    for userID, conn := range h.connections {\n        err := conn.ws.WriteMessage(websocket.TextMessage, []byte(message))\n        if err != nil {\n            fmt.Println(\"[x] Broadcast to\", userID, \"failed:\", err)\n            conn.ws.Close()\n            delete(h.connections, userID)\n        }\n    }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch3>📝 Function Summary\u003C\u002Fh3>\u003Cfigure class=\"table\">\u003Ctable>\u003Cthead>\u003Ctr>\u003Cth>Function\u003C\u002Fth>\u003Cth>Purpose\u003C\u002Fth>\u003C\u002Ftr>\u003C\u002Fthead>\u003Ctbody>\u003Ctr>\u003Ctd>AddConnection\u003C\u002Ftd>\u003Ctd>Add a new WebSocket connection\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>RemoveConnection\u003C\u002Ftd>\u003Ctd>Remove a disconnected WebSocket client\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>SendToUser\u003C\u002Ftd>\u003Ctd>Send a private message to one user\u003C\u002Ftd>\u003C\u002Ftr>\u003Ctr>\u003Ctd>Broadcast\u003C\u002Ftd>\u003Ctd>Send a message to all connected users\u003C\u002Ftd>\u003C\u002Ftr>\u003C\u002Ftbody>\u003C\u002Ftable>\u003C\u002Ffigure>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>✅ Full Code: \u003Ccode inline=\"\">main()\u003C\u002Fcode> and \u003Ccode inline=\"\">wsHandler()\u003C\u002Fcode>\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">package main\n\nimport (\n    \"fmt\"\n    \"net\u002Fhttp\"\n    \"github.com\u002Fgorilla\u002Fwebsocket\"\n)\n\n\u002F\u002F Use previously defined Hub and Connection structs\n\nvar upgrader = websocket.Upgrader{\n    CheckOrigin: func(r *http.Request) bool {\n        return true \u002F\u002F In production, restrict to trusted origins\n    },\n}\n\n\u002F\u002F WebSocket handler\nfunc wsHandler(hub *Hub, w http.ResponseWriter, r *http.Request) {\n    ws, err := upgrader.Upgrade(w, r, nil)\n    if err != nil {\n        fmt.Println(\"[x] Upgrade error:\", err)\n        return\n    }\n\n    userID := r.URL.Query().Get(\"user\")\n    if userID == \"\" {\n        fmt.Println(\"[x] Missing user ID\")\n        ws.Close()\n        return\n    }\n\n    hub.AddConnection(userID, ws)\n    defer hub.RemoveConnection(userID)\n\n    for {\n        _, msg, err := ws.ReadMessage()\n        if err != nil {\n            fmt.Println(\"[x] Read error from\", userID, \":\", err)\n            break\n        }\n\n        fmt.Printf(\"[&gt;] Received from %s: %s\\n\", userID, string(msg))\n        broadcastMsg := fmt.Sprintf(\"%s says: %s\", userID, string(msg))\n        hub.Broadcast(broadcastMsg)\n    }\n}\n\nfunc main() {\n    hub := NewHub()\n\n    http.HandleFunc(\"\u002Fws\", func(w http.ResponseWriter, r *http.Request) {\n        wsHandler(hub, w, r)\n    })\n\n    fmt.Println(\"🚀 WebSocket server started at :8080\")\n    err := http.ListenAndServe(\":8080\", nil)\n    if err != nil {\n        fmt.Println(\"[x] Server failed:\", err)\n    }\n}\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔗 How the Connection Works\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>When a user connects via:\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext\">ws:\u002F\u002Flocalhost:8080\u002Fws?user=alice\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>The system will:\u003C\u002Fp>\u003Col>\u003Cli>Parse \u003Ccode inline=\"\">userID = alice\u003C\u002Fcode>\u003C\u002Fli>\u003Cli>Store the WebSocket connection\u003C\u002Fli>\u003Cli>Accept messages from Alice\u003C\u002Fli>\u003Cli>Broadcast the message to all users\u003C\u002Fli>\u003Cli>Remove Alice’s connection if disconnected\u003C\u002Fli>\u003C\u002Fol>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>💡 What This Code Can Do\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>✅ Track and manage each WebSocket connection\u003Cbr>✅ Send private and broadcast messages\u003Cbr>✅ Automatically remove disconnected users\u003Cbr>✅ Support multiple users concurrently\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Chr>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔧 Challenge: Add Connection Timeout\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>Try implementing timeout logic to remove idle users automatically:\u003C\u002Fp>\u003Cpre>\u003Ccode class=\"language-plaintext language-go\">time.AfterFunc(10*time.Minute, func() {\n    hub.RemoveConnection(userID)\n})\n\u003C\u002Fcode>\u003C\u002Fpre>\u003Cp>Or use \u003Ccode inline=\"\">ping\u002Fpong\u003C\u002Fcode> frames to detect connection liveness.\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Ch2>🔜 Coming Up Next…\u003C\u002Fh2>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp>EP.81 – Real-Time DB Integration with WebSocket\u003Cbr>We’ll explore how to sync every message or user event to a database instantly via WebSocket!\u003C\u002Fp>\u003Cp>&nbsp;\u003C\u002Fp>\u003Cp data-start=\"498\" data-end=\"834\">\u003Cstrong>Read more\u003C\u002Fstrong>\u003C\u002Fp>\u003Cul>\u003Cli>\u003Cp data-start=\"498\" data-end=\"834\">\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002Fblogs\u002Fcategories\u002FGolang\">\u003Cstrong>Golang The Series\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003C\u002Fli>\u003Cli>\u003Cp data-start=\"498\" data-end=\"834\">\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002Fblogs\u002Fcategories\u002FJS2GO\">\u003Cstrong>JS2GO\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003C\u002Fli>\u003Cli>\u003Cp data-start=\"498\" data-end=\"834\">\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002Fen\u002Fblogs\u002Fcategories\u002FTailwind%20CSS\">\u003Cstrong>10 Eps That Will Make You a Pro Tailwind CSS Overnight\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003C\u002Fli>\u003C\u002Ful>\u003Cp>\u003Cstrong>🔵 Facebook: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.facebook.com\u002Fsuperdev.school.th\">\u003Cstrong>Superdev School &nbsp;(Superdev)\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003Cp>\u003Cstrong>📸 Instagram: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.instagram.com\u002Fsuperdevschool\u002F\">\u003Cstrong>superdevschool\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003Cp>\u003Cstrong>🎬 TikTok: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.tiktok.com\u002F@superdevschool\">\u003Cstrong>superdevschool\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>\u003Cp class=\"\" data-start=\"5978\" data-end=\"6095\">\u003Cstrong>🌐 Website: \u003C\u002Fstrong>\u003Ca target=\"_blank\" rel=\"noopener noreferrer\" href=\"https:\u002F\u002Fwww.superdev.school\u002F\">\u003Cstrong>www.superdev.school\u003C\u002Fstrong>\u003C\u002Fa>\u003C\u002Fp>","132_11zon_brcnzjni17.webp","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclblg987654321\u002Fdqkoa5wzx8l9os7\u002F132_11zon_brcnzjni17.webp","2026-03-04 08:46:59.023Z","",{"keywords":15,"locale":38,"school_blog":48},[16,23,28,33],{"collectionId":17,"collectionName":18,"created":19,"created_by":13,"id":20,"name":21,"updated":22,"updated_by":13},"sclkey987654321","school_keywords","2026-03-04 08:20:11.547Z","ey3puyme01a9bsw","Go","2026-04-10 16:07:25.893Z",{"collectionId":17,"collectionName":18,"created":24,"created_by":13,"id":25,"name":26,"updated":27,"updated_by":13},"2026-03-04 08:20:14.253Z","ah6lvy4x8qe08l5","Golang","2026-04-10 16:07:26.172Z",{"collectionId":17,"collectionName":18,"created":29,"created_by":13,"id":30,"name":31,"updated":32,"updated_by":13},"2026-03-04 08:34:00.920Z","ecac9y661or1xka","WebSocket","2026-04-10 16:08:05.227Z",{"collectionId":17,"collectionName":18,"created":34,"created_by":13,"id":35,"name":36,"updated":37,"updated_by":13},"2026-03-04 08:44:37.391Z","krqs9dt45y5ixau","Connection Management","2026-04-10 16:12:47.710Z",{"code":39,"collectionId":40,"collectionName":41,"created":42,"flag":43,"id":44,"is_default":45,"label":46,"updated":47},"en","pbc_1989393366","locales","2026-01-22 11:00:02.726Z","twemoji:flag-united-states","qv9c1llfov2d88z",false,"English","2026-04-10 15:42:46.825Z",{"category":49,"collectionId":50,"collectionName":51,"expand":52,"id":66,"views":67},"wqxt7ag2gn7xcmk","pbc_2105096300","school_blogs",{"category":53},{"blogIds":54,"collectionId":55,"collectionName":56,"created":57,"created_by":13,"id":49,"image":58,"image_alt":13,"image_path":59,"label":60,"name":61,"priority":62,"publish_at":63,"scheduled_at":13,"status":64,"updated":65,"updated_by":13},[],"sclcatblg987654321","school_category_blogs","2026-03-04 08:33:53.210Z","59ty92ns80w_15oc1implw.png","https:\u002F\u002Ftwsme-r2.tumwebsme.com\u002Fsclcatblg987654321\u002Fwqxt7ag2gn7xcmk\u002F59ty92ns80w_15oc1implw.png",{"en":61,"th":61},"Golang The Series",1,"2026-03-16 04:39:38.440Z","published","2026-04-25 02:32:15.470Z","bebwb61pxsyy11j",215,"dqkoa5wzx8l9os7",[20,25,30,35],"2025-08-26 02:34:46.682Z","Learn how to manage connections in a WebSocket-based chat system using Go — from adding\u002Fremoving users to private and broadcast messaging — ensuring your server can scale and remain stable with many concurrent users.","golang-websocket-connection-management","2026-04-25 02:48:10.997Z",{"en":72}]