{"id":13575352,"url":"https://github.com/hezhizheng/go-gin-chat","last_synced_at":"2025-05-16T03:06:08.614Z","repository":{"id":37629041,"uuid":"302895851","full_name":"hezhizheng/go-gin-chat","owner":"hezhizheng","description":"Golang(Gin)+websocket 的多人聊天室  | go 聊天室  | golang 聊天室 ","archived":false,"fork":false,"pushed_at":"2025-03-20T11:08:23.000Z","size":11490,"stargazers_count":411,"open_issues_count":2,"forks_count":86,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-08T14:06:50.591Z","etag":null,"topics":["chat","chatroom","gin","gin-chat","gin-websocket","go","golang","websocket"],"latest_commit_sha":null,"homepage":"https://chat.hzz.cool/","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/hezhizheng.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","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":"2020-10-10T12:23:15.000Z","updated_at":"2025-04-01T02:44:38.000Z","dependencies_parsed_at":"2024-06-20T05:42:49.344Z","dependency_job_id":"97dc4d09-6d16-4be3-9b2a-f59d6828d886","html_url":"https://github.com/hezhizheng/go-gin-chat","commit_stats":{"total_commits":65,"total_committers":2,"mean_commits":32.5,"dds":0.03076923076923077,"last_synced_commit":"abd003dc179def9caedcfa920559968edb9b761e"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hezhizheng%2Fgo-gin-chat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hezhizheng%2Fgo-gin-chat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hezhizheng%2Fgo-gin-chat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hezhizheng%2Fgo-gin-chat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hezhizheng","download_url":"https://codeload.github.com/hezhizheng/go-gin-chat/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254459088,"owners_count":22074605,"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":["chat","chatroom","gin","gin-chat","gin-websocket","go","golang","websocket"],"created_at":"2024-08-01T15:01:00.259Z","updated_at":"2025-05-16T03:06:03.606Z","avatar_url":"https://github.com/hezhizheng.png","language":"Go","funding_links":[],"categories":["Go"],"sub_categories":[],"readme":"# go-gin-chat(Gin+websocket 的多人聊天室)\n\n\u003e 练手小项目，为熟悉Gin框架跟websocket使用 💛💛💛💛💛💛\n\n\u003e [在线demo](https://chat.hzz.cool/) (PS: 请尽量使用Chrome游览器，开启多个不同用户游览器即可体验效果)\n\n\u003e [github地址](https://github.com/hezhizheng/go-gin-chat)\n\n## Feature\n- 登录/注册(防止重复登录)\n- 群聊(多房间、支持文字、emoji、文件(图片)上传，使用 ~~[freeimage.host](https://freeimage.host/)~~ 做图床 )\n  - freeimage.host 不同地区可能会被墙，可选使用 smms.app / sm.ms 做图床\n- 私聊(消息提醒)\n- 历史消息查看(点击加载更多)\n- 心跳检测及自动重连机制，来自 https://github.com/zimv/websocket-heartbeat-js\n- go mod 包管理\n- 使用 Golang 1.16 embed 内嵌静态资源(html、js、css等)，运行只依赖编译好的可执行文件与mysql\n- 支持 http/ws 、 https/wss\n\n## 结构\n```\n.\n|-- LICENSE.txt\n|-- conf #配置文件\n|   |-- config.go\n|   `-- config.go.env\n|-- controller\n|   |-- ImageController.go\n|   `-- IndexController.go\n|-- main.go\n|-- models\n|   |-- message.go\n|   |-- mysql.go\n|   `-- user.go\n|-- routes\n|   `-- route.go\n|-- services # 简单逻辑处理服务层\n|   |-- helper\n|   |   `-- helper.go\n|   |-- img_kr\n|   |   `-- imgKr.go\n|   |-- message_service\n|   |   `-- message.go\n|   |-- session\n|   |   `-- session.go\n|   |-- user_service\n|   |   `-- user.go\n|   `-- validator\n|       `-- validator.go\n|-- sql\n|   `-- go_gin_chat.sql\n|-- static #静态文件 js 、css 、image 目录\n|-- views\n|   |-- index.html\n|   |-- login.html\n|   |-- private_chat.html\n|   `-- room.html\n`-- ws websocket 服务端主要逻辑\n    |-- ServeInterface.go \n    |-- go_ws\n    |   `-- serve.go # websocket服务端处理代码\n    |-- primary\n    |   `-- start.go # 为了兼容新旧版 websocket服务端 的调用策略\n    |-- serve.go # 初版websocket服务端逻辑代码，可以忽略\n    `-- ws_test #本地测试代码\n        |-- exec.go\n        `-- mock_ws_client_coon.go\n```\n\n## 伪代码，详情可参考 [serve.go](./ws/go_ws/serve.go)\n- 定义客户端信息的结构体\n```go\ntype wsClients struct {\nConn *websocket.Conn `json:\"conn\"`\n\nRemoteAddr string `json:\"remote_addr\"`\n\nUid float64 `json:\"uid\"`\n\nUsername string `json:\"username\"`\n\nRoomId string `json:\"room_id\"`\n\nAvatarId string `json:\"avatar_id\"`\n}\n\n// \n```\n- 定义全局变量\n```go\n\n// client \u0026 serve 的消息体\ntype msg struct {\nStatus int             `json:\"status\"`\nData   interface{}     `json:\"data\"`\nConn   *websocket.Conn `json:\"conn\"`\n}\n\n// 上线、离线、消息发送事件 的 无缓冲区的 channel\nvar (\nclientMsg = msg{}\n\nenterRooms = make(chan wsClients)\n\nsMsg = make(chan msg)\n\noffline = make(chan *websocket.Conn)\n\nchNotify = make(chan int ,1)\n)\n```  \n- 使用 make 创建一个全局的 `map slice` 用于存放房间与用户的信息，用户上线、离线实际上是对map的 append 跟 remove\n```go\nvar (\nrooms = make(map[int][]wsClients)\n)\n```\n- 开启`goroutine`处理用户的连接、离线、消息发送等各个事件\n```go\ngo read(c)\ngo write()\nselect {}\n```\n\n\n\n## 界面\n![](https://static01.imgkr.com/temp/5c3c9096ef9f4796b404dd2f3e23c36d.png)\n![](https://static01.imgkr.com/temp/cd66af62792f4d2e8c2fa974e82d0526.png)\n![](https://static01.imgkr.com/temp/099bf697686445d79407962cdfb11e56.png)\n![](https://static01.imgkr.com/temp/1e89fdd024de47fa862143fba246d632.png)\n\n## database\n#### mysql\n```\nCREATE TABLE `messages`  (\n  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,\n  `user_id` int(11) NOT NULL COMMENT '用户ID',\n  `room_id` int(11) NOT NULL COMMENT '房间ID',\n  `to_user_id` int(11) NULL DEFAULT 0 COMMENT '私聊用户ID',\n  `content` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '聊天内容',\n  `image_url` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '图片URL',\n  `created_at` datetime(0) NULL DEFAULT NULL,\n  `updated_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),\n  `deleted_at` datetime(0) NULL DEFAULT NULL,\n  PRIMARY KEY (`id`) USING BTREE,\n  INDEX `idx_user_id`(`user_id`) USING BTREE\n) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC;\n\nCREATE TABLE `users`  (\n  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,\n  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT '昵称',\n  `password` varchar(125) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '' COMMENT '密码',\n  `avatar_id` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '1' COMMENT '头像ID',\n  `created_at` datetime(0) NULL DEFAULT NULL,\n  `updated_at` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),\n  `deleted_at` datetime(0) NULL DEFAULT NULL,\n  PRIMARY KEY (`id`) USING BTREE,\n  UNIQUE INDEX `username`(`username`) USING BTREE\n) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC;\n\n```\n \n## Tools\n- [模板提供](https://github.com/zfowed/charooms-html) \n- github.com/gin-gonic/gin\n- gorm.io/driver/mysql\n- gorm.io/gorm\n- github.com/gravityblast/fresh\n- github.com/valyala/fasthttp\n- github.com/spf13/viper\n\n## 使用 (go version \u003e= 1.16)\n\n```\n# 自行导入数据库文件 sql/go_gin_chat.sql\ngit clone github.com/hezhizheng/go-gin-chat\ncd go-gin-chat\ncp conf/config.go.env conf/config.go // 根据实际情况修改配置\ngo run main.go \n```\n\n## nginx 部署\n\n```\nserver {\n    listen 80;\n    listen 443 ssl http2;\n    server_name  go-gin-chat.hzz.cool;\n\n    #ssl on;  \n    ssl_certificate xxxpath\\cert.pem;   \n    ssl_certificate_key xxxpath\\key.pem;   \n    ssl_session_timeout  5m;  \n    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;  \n    ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;  \n    ssl_prefer_server_ciphers  on;\n\n    location ~ .*\\.(gif|jpg|png|css|js)(.*) {\n                proxy_pass http://127.0.0.1:8322;\n                proxy_redirect off;\n                proxy_set_header Host $host;\n                proxy_cache cache_one;\n                proxy_cache_valid 200 302 24h;\n                proxy_cache_valid 301 30d;\n                proxy_cache_valid any 5m;\n                expires 90d;\n                add_header wall  \"Big brother is watching you\";\n    }\n  \n\n   location / {\n       try_files /_not_exists_ @backend;\n   }\n  \n   location @backend {\n        proxy_set_header X-Forwarded-For $remote_addr;\n        proxy_set_header Host            $http_host;\n\n        proxy_pass http://127.0.0.1:8322;\n    }\n  \n   location /ws {\n        proxy_pass http://127.0.0.1:8322;\n        proxy_redirect off;\n        proxy_http_version 1.1;\n\n        proxy_set_header Upgrade $http_upgrade;\n        proxy_set_header Connection \"upgrade\";\n\n        proxy_set_header Host $host:$server_port;\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    \n        proxy_read_timeout 6000s;\n   }\n```\n## 编译可执行文件(跨平台)\n\n```\n# 用法参考 https://github.com/mitchellh/gox\n# go install github.com/mitchellh/gox@latest (go 1.18)\n# 生成文件可直接执行 Linux\ngox -osarch=\"linux/amd64\" -ldflags \"-s -w\" -gcflags=\"all=-trimpath=${PWD}\" -asmflags=\"all=-trimpath=${PWD}\"\n......\n```\n\n\n## TODO\n- [x] 心跳机制\n- [x] 多频道聊天\n- [x] 私聊\n- [x] 在线用户列表\n- [x] https支持\n\n## License\n[MIT](./LICENSE.txt)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhezhizheng%2Fgo-gin-chat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhezhizheng%2Fgo-gin-chat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhezhizheng%2Fgo-gin-chat/lists"}