{"id":28917119,"url":"https://github.com/eyasliu/cs","last_synced_at":"2025-08-02T20:33:56.681Z","repository":{"id":43929925,"uuid":"330363301","full_name":"eyasliu/cs","owner":"eyasliu","description":"开箱即用的基于命令的消息处理框架，让 websocket 和 tcp 开发就像 http 那样简单","archived":false,"fork":false,"pushed_at":"2023-11-29T07:35:33.000Z","size":107,"stargazers_count":21,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-22T00:11:50.777Z","etag":null,"topics":["http-server","sse","tcp","tcp-server","websocket","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/eyasliu.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":"2021-01-17T10:17:43.000Z","updated_at":"2023-11-23T10:53:19.000Z","dependencies_parsed_at":"2024-06-19T05:22:04.126Z","dependency_job_id":"3a45a0e8-5884-4533-ac15-f6a1ce66b4e1","html_url":"https://github.com/eyasliu/cs","commit_stats":null,"previous_names":["eyasliu/cmdsrv"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/eyasliu/cs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eyasliu%2Fcs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eyasliu%2Fcs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eyasliu%2Fcs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eyasliu%2Fcs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eyasliu","download_url":"https://codeload.github.com/eyasliu/cs/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eyasliu%2Fcs/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":268448362,"owners_count":24252019,"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","status":"online","status_checked_at":"2025-08-02T02:00:12.353Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["http-server","sse","tcp","tcp-server","websocket","websocket-server"],"created_at":"2025-06-22T00:11:43.075Z","updated_at":"2025-08-02T20:33:56.668Z","avatar_url":"https://github.com/eyasliu.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Command Service\n\n[![Build Status](https://travis-ci.com/eyasliu/cs.svg)](https://travis-ci.com/eyasliu/cs)\n[![Go Doc](https://godoc.org/github.com/eyasliu/cs?status.svg)](https://godoc.org/github.com/eyasliu/cs)\n[![Code Coverage](https://codecov.io/gh/eyasliu/cs/branch/master/graph/badge.svg)](https://codecov.io/gh/eyasliu/cs/branch/master)\n[![License](https://img.shields.io/github/license/eyasliu/cs.svg?style=flat)](https://github.com/eyasliu/cs)\n\n开箱即用的基于命令的消息处理框架，让 websocket 和 tcp 开发就像 http 那样简单\n\n# 使用示例\n\n\n```go\npackage main\nimport (\n  \"net/http\"\n  \"github.com/eyasliu/cs\"\n  \"github.com/eyasliu/cs/xwebsocket\"\n)\n\nfunc main() {\n  // 初始化 websocket\n  ws := xwebsocket.New()\n  http.Handle(\"/ws\", ws)\n\n  srv := ws.Srv()\n  srv.Use(cs.AccessLogger(\"MYSRV\")). // 打印请求响应日志\n            Use(cs.Recover()) // 统一错误处理，消化 panic 错误\n\n  srv.Handle(\"register\", func(c *cs.Context) {\n    // 定义请求数据\n    var body struct {\n      UID  int    `p:\"uid\" v:\"required\"`\n      Name string `p:\"name\" v:\"required|min:4#必需指定名称|名称长度必需大于4位\"`\n    }\n    // 解析请求数据\n    if err := c.Parse(\u0026body); err != nil {\n      c.Err(err, 401)\n      return\n    }\n    // 设置会话状态数据\n    c.Set(\"uid\", body.UID)\n    c.Set(\"name\", body.Name)\n\n    // 响应消息\n    c.OK(map[string]interface{}{\n      \"timestamp\": time.Now().Unix(),\n    })\n\n    // 给所有连接广播消息\n    c.Broadcast(\u0026cs.Response{\n      Cmd:  \"someone_online\",\n      Data: body,\n    })\n\n    // 往当前连接主动推送消息\n    c.Push(\u0026cs.Response{\n      Cmd:  \"welcome\",\n      Data: \"welcome to register my server\",\n    })\n\n    // 遍历所有在线会话，获取其他会话的状态，并往指定会话推送消息\n    for _, sid := range c.GetAllSID() {\n      if c.Srv.GetState(sid, \"uid\") != nil {\n        c.Srv.Push(sid, \u0026cs.Response{\n          Cmd:  \"firend_online\",\n          Data: \"your firend is online\",\n        })\n      }\n    }\n  })\n\n  // 分组\n  group := srv.Group(func(c *cs.Context) {\n    // 过滤指定请求\n    if _, ok := c.Get(\"uid\").(int); !ok {\n      c.Err(errors.New(\"unregister session\"), 101)\n      return\n    }\n    c.Next()\n  })\n\n  group.Handle(\"userinfo\", func(c *cs.Context) {\n    uid := c.Get(\"uid\").(int) // 中间件已处理过，可大胆断言\n    c.OK(map[string]interface{}{\n      \"uid\": uid,\n    })\n  })\n  go srv.Run()\n\n  http.ListenAndServe(\":8080\", nil)\n}\n```\n\n\n### 适配器\n\n[用在 websocket](./xwebsocket)\n\n```go\nimport (\n  \"net/http\"\n  \"github.com/eyasliu/cs/xwebsocket\"\n)\n\nfunc main() {\n  ws := xwebsocket.New()\n  http.Handler(\"/ws\", ws.Handler)\n  srv := ws.Srv(ws)\n  go srv.Run()\n\n  http.ListenAndServe(\":8080\", nil)\n}\n```\n\n[用在 TCP](./xtcp)，使用内置默认协议\n\n```go\nimport (\n  \"github.com/eyasliu/cs/xtcp\"\n)\n\nfunc main() {\n  server := xtcp.New(\"127.0.0.1:8520\")\n  srv, err := server.Srv()\n  if err != nil {\n    panic(err)\n  }\n\n  srv.Run() // 阻塞运行\n}\n```\n\n[用在 HTTP](./xhttp)，支持请求响应，支持服务器主动推送\n\n```go\nimport (\n  \"net/http\"\n  \"github.com/eyasliu/cs\"\n  \"github.com/eyasliu/cs/xhttp\"\n)\n\nfunc main() {\n  server := xhttp.New()\n  http.Handle(\"/cmd\", server)\n  http.HandleFunc(\"/cmd2\", server.Handler)\n  srv := server.Srv()\n  go http.ListenAndServe(\":8080\", nil)\n\t\n  srv.Run()\n}\n```\n\n多个适配器混用，让 websocket, tcp, http 共用同一套逻辑\n\n```go\nimport (\n  \"net/http\"\n  \"github.com/eyasliu/cs\"\n  \"github.com/eyasliu/cs/xhttp\"\n  \"github.com/eyasliu/cs/xwebsocket\"\n  \"github.com/eyasliu/cs/xtcp\"\n)\n\nfunc main() {\n  // http adapter\n  server := xhttp.New()\n  http.Handle(\"/cmd\", server)\n  http.HandleFunc(\"/cmd2\", server.Handler)\n  \n  // websocket adapter\n  ws := xwebsocket.New()\n  http.Handle(\"/ws\", server)\n\n  // tcp adapter\n  tcp := xtcp.New()\n\n  // boot srv\n  go tcp.Run()\n  go http.ListenAndServe(\":8080\", nil)\n\n  srv := cs.New(server, ws, tcp)\n  srv.Run() // 阻塞运行\n}\n```\n\n```sh\n$ curl -XPOST -H\"Content-Type:application/json\" --data '{\"cmd\":\"register\", \"data\":{\"uid\": 101, \"name\": \"eyasliu\"}}' http://localhost:8080/cmd\n{\"cmd\":\"register\",\"data\":{\"timestamp\": 1610960488}}\n```\n\n# 实现过程\n\n在开发 websocket 和 tcp 的时候，对于长连接的消息处理都需要手动处理，并没有类似于 http 的路由那么方便，于是就想要实现一个可以处理该类消息的工具。\n\n在长连接的开发中，经常遇到的一些问题：\n\n 1. 每个连接会话在连接后都需要注册，以标识该连接的用途\n 2. 每个请求都需要处理，并且保证一定有响应\n 3. 往连接主动推送消息\n 4. 给所有连接广播消息\n 5. 消息处理的代码不够优雅，太多 switch case 等样板代码\n 6. 请求的数据解析不好写\n\n实现方案：\n\n在 websocket 和 tcp 中，每个连接都抽象成一个字符串 `SID`, 即 Session ID, cs 只负责处理消息，不处理连接的任何状态，与连接和状态相关的操作全都以 interface 定义好，给各种工具去实现\n\n## API\n\n[GoDoc](https://pkg.go.dev/github.com/eyasliu/cs)\n\n\n\n## License\n\ncs is released under the \n[MIT License](http://opensource.org/licenses/mit-license.php).\n\n(c) 2020-2021 Eyas Liu \u003cliuyuesongde@163.com\u003e\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feyasliu%2Fcs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feyasliu%2Fcs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feyasliu%2Fcs/lists"}