{"id":20737207,"url":"https://github.com/aspiesoft/go-websocket","last_synced_at":"2025-04-24T01:42:15.765Z","repository":{"id":65388493,"uuid":"589354507","full_name":"AspieSoft/go-websocket","owner":"AspieSoft","description":"An easy way to get started with websockets in golang.","archived":false,"fork":false,"pushed_at":"2024-08-06T18:00:36.000Z","size":55,"stargazers_count":18,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-06T11:47:33.570Z","etag":null,"topics":["go","golang","javascript","js","websocket","websocket-client","websocket-server"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/AspieSoft.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-01-15T22:16:14.000Z","updated_at":"2024-08-06T18:07:59.000Z","dependencies_parsed_at":"2023-02-18T14:31:01.292Z","dependency_job_id":"7ffcbfa7-6537-4823-93c4-f60f9d3feec0","html_url":"https://github.com/AspieSoft/go-websocket","commit_stats":{"total_commits":39,"total_committers":1,"mean_commits":39.0,"dds":0.0,"last_synced_commit":"d663cff7871325d8c83c851499db4d9ec01f7a90"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AspieSoft%2Fgo-websocket","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AspieSoft%2Fgo-websocket/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AspieSoft%2Fgo-websocket/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/AspieSoft%2Fgo-websocket/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/AspieSoft","download_url":"https://codeload.github.com/AspieSoft/go-websocket/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250545690,"owners_count":21448247,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","golang","javascript","js","websocket","websocket-client","websocket-server"],"created_at":"2024-11-17T06:13:51.081Z","updated_at":"2025-04-24T01:42:15.747Z","avatar_url":"https://github.com/AspieSoft.png","language":"Go","funding_links":["https://paypal.me/shaynejrtaylor?country.x=US\u0026locale.x=en_US"],"categories":[],"sub_categories":[],"readme":"# Go WebSocket\n\n[![donation link](https://img.shields.io/badge/buy%20me%20a%20coffee-paypal-blue)](https://paypal.me/shaynejrtaylor?country.x=US\u0026locale.x=en_US)\n\nAn easy way to get started with websockets in golang.\n\nThis module tracks user sessions, can recover temporarily lost connections, and compresses data through gzip if supported by the client.\n\n## Installation\n\n### Go (server)\n\n```shell script\ngo get github.com/AspieSoft/go-websocket\n```\n\n### JavaScript (client)\n\n```html\n\u003cscript src=\"https://cdn.jsdelivr.net/gh/AspieSoft/go-websocket@1.4.8/client.min.js\" defer\u003e\u003c/script\u003e\n```\n\n## Usage\n\n### Go (server)\n\n```go\n\nimport (\n  \"net/http\"\n\n  \"github.com/AspieSoft/go-websocket\"\n)\n\nfunc main(){\n  // setup a new websocket server\n  server := websocket.NewServer(\"https://www.example.com\")\n  http.Handle(\"/ws\", server.Handler())\n\n  // optional: set a timeout for when disconnected clients can no longer reconnect with the same data\n  server := websocket.NewServer(\"https://www.example.com\", 30 * time.Second)\n\n  // by default, data is compressed with gzip before being send between the server and client\n  // this behavior can opptonally be disabled\n  server.Gzip = false\n\n  // by default, the server only reads requests up to 1 megabyte\n  // this value can opptionally be changed\n  server.ReqSize = 1024 // KB\n\n\n  static := http.FileServer(http.Dir(\"./public/\"))\n  http.Handle(\"/\", static)\n\n  server.Connect(func(client *websocket.Client){\n    // client connected\n\n    // localstorage that stays with the client, and verifies their session\n    // map[string]interface{}\n    client.Store[\"key\"] = \"value\"\n\n    server.Broadcast(\"notify\", \"a new user connected to the server\")\n    server.Broadcast(\"user\", client.ClientID)\n\n    client.On(\"message\", func(msg interface{}) {\n      // client sent a message\n\n      // optional: enforce a specific message type\n      str := websocket.ToType[string](msg)\n      b := websocket.ToType[[]byte](msg)\n      i := websocket.ToType[int](msg)\n      bool := websocket.ToType[bool](msg)\n      json := websocket.ToType[map[string]interface{}](msg)\n      array := websocket.ToType[[]interface{}](msg)\n    })\n\n    // send data to client\n    client.Send(\"message\", \"my message to the client\")\n\n    client.Send(\"json\", map[string]interface{}{\n      \"jsondata\": \"my json data\",\n      \"key\": \"value\",\n      \"a\": 1,\n    })\n\n    client.on(\"send-to-friend\", func(msg interface{}){\n      json := websocket.ToType[map[string]interface{}](msg)\n\n      // send a message to a different client\n      server.send(json[\"friendsClientID\"], json[\"msg\"])\n\n      // do other stuff...\n      client.send(\"send-from-friend\", map[string]interface{\n        \"ClientID\": client.ClientID,\n        \"msg\": \"General Kenobi!\",\n      })\n    })\n\n    client.Disconnect(func(code int) {\n      // when client disconnects\n      server.Broadcast(\"disconnected\", client.ClientID)\n    })\n  })\n\n  server.On(\"kick\", func(client *websocket.Client, msg interface{}) {\n    friendsClientID := websocket.ToType[string](msg)\n\n    // force a client to leave the server\n    server.Kick(friendsClientID, 1000)\n\n    server.Broadcast(\"kicked\", friendsClientID+\" was kicked by \"+client.ClientID)\n  })\n\n  server.On(\"kick-all\", func(client *Client, msg interface{}) {\n    // kick every client from the server\n    server.KickAll()\n  })\n\n  log.Fatal(http.ListenAndServe(\":3000\", nil))\n}\n\n```\n\n### JavaScript (client)\n\n```JavaScript\n\nconst socket = new ServerIO(); // will default to current origin\n// or\nconst socket = new ServerIO('https://www.example.com'); // optional: specify a different origin\n\nsocket.connect(function(initial){\n  // connected to server\n\n  socket.send('message', \"my message to the server\");\n\n  if(initial){\n    // very first time connecting to the server\n  }else{\n    // reconnecting after a previous disconnect\n  }\n});\n\nsocket.on('message', function(msg){\n  console.log('I got a new message:', msg);\n\n  socket.send('json', {\n    jsondata: 'my json data',\n    key: 'value',\n    a: 1,\n  });\n});\n\nsocket.on('json', function(msg){\n  console.log('pre-parsed json:', msg.jsondata);\n});\n\nsocket.on('notify', function(msg){\n  console.log(msg);\n});\n\nlet myNewFriend = null;\nsocket.on('user', function(msg){\n  myNewFriend = msg;\n\n  socket.send('send-to-friend', {\n    friendsClientID: myNewFriend,\n    msg: 'Hello, There!',\n  })\n});\n\nsocket.on('send-from-friend', function(msg){\n  socket.send('kick', myNewFriend);\n});\n\nsocket.on('kicked', function(msg){\n  socket.send('kick-all');\n\n  // run disconnect\n  socket.disconnect();\n\n  // run reconnect\n  socket.connect();\n});\n\nsocket.disconnect(function(status){\n  // on disconnect\n  if(status === 1000){\n    console.log('disconnected successfully');\n  }else if(status === 1006){\n    console.warn('error: disconnected by accident, auto reconnecting...');\n  }else{\n    console.error('error:', status);\n  }\n});\n\n\nsocket.on('notifications', function(){\n  console.log('my notification');\n})\n\n// stop listining to a message, and remove all client listeners of that type\nsocket.off('notifications');\n\n// stop the server from sending messages, but keep the listener on the client\nsocket.off('notifications', false);\n\n// request the server to send messages again\nsocket.on('notifications');\n\n\nsocket.error(function(type){\n  // handle errors\n  // Note: disconnection errors will Not trigger this method\n\n  if(type === 'migrate'){\n    // the client reconnected to the server, but the server failed to migrate the clients old data to the new connection\n    // client listeners should still automatically be restored\n  }\n});\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faspiesoft%2Fgo-websocket","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faspiesoft%2Fgo-websocket","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faspiesoft%2Fgo-websocket/lists"}