初始化
This commit is contained in:
8
.idea/.gitignore
generated
vendored
Normal file
8
.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/websocket.iml" filepath="$PROJECT_DIR$/.idea/websocket.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
9
.idea/websocket.iml
generated
Normal file
9
.idea/websocket.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="Go" enabled="true" />
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
41
go.mod
Normal file
41
go.mod
Normal file
@@ -0,0 +1,41 @@
|
||||
module xk-websocket
|
||||
|
||||
go 1.24.4
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.10.1
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/crypto v0.23.0 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
golang.org/x/text v0.15.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
111
go.sum
Normal file
111
go.sum
Normal file
@@ -0,0 +1,111 @@
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.10.1 h1:T0ujvqyCSqRopADpgPgiTT63DUQVSfojyME59Ei63pQ=
|
||||
github.com/gin-gonic/gin v1.10.1/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
|
||||
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
||||
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
|
||||
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
|
||||
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
677
main.go
Normal file
677
main.go
Normal file
@@ -0,0 +1,677 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// WebSocket 升级器配置
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true // 允许跨域
|
||||
},
|
||||
}
|
||||
|
||||
// 统一消息结构(发送方使用)
|
||||
type SendMessagePayload struct {
|
||||
RequestType string `json:"request_type"` // 消息类型
|
||||
TargetClientID string `json:"target_client_id"` // 目标客户端ID
|
||||
SenderUserID string `json:"sender_user_id"` // 发送者用户ID
|
||||
ReceiverUserID string `json:"receiver_user_id"` // 接收者用户ID
|
||||
MessageType int `json:"message_type"` // 消息类型(0-6)
|
||||
MessageContent string `json:"message_content"` // 消息内容
|
||||
}
|
||||
|
||||
// 通过用户ID发送消息的结构
|
||||
type SendToUserPayload struct {
|
||||
SenderUserID string `json:"sender_user_id"` // 发送者用户ID
|
||||
ReceiverUserID string `json:"receiver_user_id"` // 接收者用户ID
|
||||
MessageType int `json:"message_type"` // 消息类型(0-6)
|
||||
MessageContent string `json:"message_content"` // 消息内容
|
||||
}
|
||||
|
||||
// 客户端接收消息结构(最终格式)
|
||||
type ClientReceivedMessage struct {
|
||||
SenderID string `json:"sender_id"` // 发送者连接ID
|
||||
ReceiverID string `json:"receiver_id"` // 接收者连接ID
|
||||
SenderUserID string `json:"sender_user_id"` // 发送者用户ID
|
||||
ReceiverUserID string `json:"receiver_user_id"` // 接收者用户ID
|
||||
MessageType int `json:"message_type"` // 消息类型(0-6)
|
||||
Content string `json:"content"` // 消息内容
|
||||
SendTime string `json:"send_time"` // 发送时间
|
||||
}
|
||||
|
||||
// Redis 消息结构
|
||||
type RedisMessage struct {
|
||||
SenderNodeID string `json:"sender_node_id"` // 发送节点ID
|
||||
ClientID string `json:"client_id"` // 目标客户端ID
|
||||
Message string `json:"message"` // 消息内容
|
||||
}
|
||||
|
||||
// 用户绑定请求结构
|
||||
type BindRequest struct {
|
||||
UserID string `json:"user_id"` // 用户ID
|
||||
ClientID string `json:"client_id"` // 客户端ID
|
||||
}
|
||||
|
||||
// 全局变量
|
||||
var (
|
||||
clients = make(map[string]*websocket.Conn) // 客户端连接映射
|
||||
clientsMux sync.RWMutex // 连接映射的读写锁
|
||||
redisCtx = context.Background() // Redis 上下文
|
||||
nodeID string // 当前节点ID
|
||||
redisCli *redis.Client // Redis 客户端
|
||||
port string // 服务端口
|
||||
)
|
||||
|
||||
// Redis键常量
|
||||
const (
|
||||
ClientUserKey = "client_user_mapping" // clientid -> userid映射
|
||||
UserClientKey = "user_client_mapping" // userid -> clientid列表
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 配置系统
|
||||
configureSystem()
|
||||
|
||||
// 初始化Redis客户端
|
||||
initRedisClient()
|
||||
|
||||
// 创建Gin路由器
|
||||
router := gin.Default()
|
||||
router.Use(gin.Recovery()) // 添加恢复中间件
|
||||
|
||||
// 注册路由
|
||||
router.GET("/ws", handleWebSocket) // WebSocket连接端点
|
||||
router.POST("/send", sendMessageHandler) // 消息发送端点(通过客户端ID)
|
||||
router.POST("/bind", bindHandler) // 用户绑定端点
|
||||
router.POST("/send-to-user", sendToUserHandler) // 新增:通过用户ID发送消息
|
||||
router.GET("/health", healthHandler) // 健康检查端点
|
||||
|
||||
// 输出启动信息
|
||||
printStartupInfo()
|
||||
|
||||
// 启动Redis消息订阅
|
||||
go subscribeToRedis()
|
||||
|
||||
// 启动HTTP服务
|
||||
runServer(router)
|
||||
}
|
||||
|
||||
// 配置系统环境
|
||||
func configureSystem() {
|
||||
nodeID = getEnv("NODE_ID", "local") // 获取节点ID,默认"local"
|
||||
port = getEnv("PORT", "12080") // 获取端口,默认12080
|
||||
log.SetPrefix(fmt.Sprintf("[Node:%s] ", nodeID)) // 设置日志前缀
|
||||
log.SetFlags(log.LstdFlags | log.Lmicroseconds) // 设置日志格式
|
||||
}
|
||||
|
||||
// 初始化Redis客户端
|
||||
func initRedisClient() {
|
||||
redisAddr := getEnv("REDIS_ADDR", "localhost:6379")
|
||||
redisPassword := getEnv("REDIS_PASSWORD", "") // Redis密码
|
||||
redisCli = redis.NewClient(&redis.Options{
|
||||
Addr: redisAddr, // Redis地址
|
||||
Password: redisPassword, // Redis密码
|
||||
DB: 0, // 默认DB
|
||||
})
|
||||
|
||||
// 测试Redis连接
|
||||
if err := checkRedisConnection(); err != nil {
|
||||
log.Fatalf("❌ Redis连接失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 检查Redis连接
|
||||
func checkRedisConnection() error {
|
||||
_, err := redisCli.Ping(redisCtx).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
// 输出启动信息
|
||||
func printStartupInfo() {
|
||||
hostname, _ := os.Hostname()
|
||||
log.Printf("🚀 WebSocket服务启动: NodeID=%s", nodeID)
|
||||
log.Printf("🌐 监听端口: %s", port)
|
||||
log.Printf("📡 Redis地址: %s", getEnv("REDIS_ADDR", "localhost:6379"))
|
||||
log.Printf("💻 主机: %s", hostname)
|
||||
log.Printf("🕒 启动时间: %s", time.Now().Format("2006-01-02 15:04:05"))
|
||||
log.Printf("🔔 支持消息类型: 0:文本 1:图片 2:音频 3:视频 4:处方 5:病例 6:视频通话")
|
||||
log.Printf("🔑 用户绑定键: %s, %s", ClientUserKey, UserClientKey)
|
||||
log.Printf("📬 新增接口: POST /send-to-user (直接通过用户ID发送消息)")
|
||||
log.Println("🔗 等待客户端连接...")
|
||||
}
|
||||
|
||||
// 启动服务
|
||||
func runServer(router *gin.Engine) {
|
||||
addr := "127.0.0.1:" + port
|
||||
log.Printf("🔌 服务地址: http://%s", addr)
|
||||
log.Printf("🔌 WebSocket连接地址: ws://%s/ws", addr)
|
||||
|
||||
if err := router.Run(addr); err != nil {
|
||||
log.Fatalf("❌ 服务启动失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 健康检查处理
|
||||
func healthHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "ok",
|
||||
"node": nodeID,
|
||||
"time": time.Now().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
|
||||
// WebSocket处理函数
|
||||
func handleWebSocket(c *gin.Context) {
|
||||
start := time.Now()
|
||||
clientIP := c.ClientIP()
|
||||
|
||||
log.Printf("👤 客户端连接中: IP=%s", clientIP)
|
||||
|
||||
// 升级为WebSocket连接
|
||||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
log.Printf("⚠️ WebSocket升级失败: %v | ClientIP=%s", err, clientIP)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无法升级为WebSocket连接"})
|
||||
return
|
||||
}
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
// 生成客户端ID
|
||||
clientID := generateClientID()
|
||||
log.Printf("✅ 客户端已连接: ClientID=%s | IP=%s | Duration=%s",
|
||||
clientID, clientIP, time.Since(start))
|
||||
|
||||
// 将连接添加到客户端映射
|
||||
addClient(clientID, conn)
|
||||
defer removeClient(clientID)
|
||||
|
||||
// 发送客户端ID
|
||||
if err := conn.WriteJSON(gin.H{"clientId": clientID}); err != nil {
|
||||
log.Printf("⚠️ 发送客户端ID失败: %v | ClientID=%s", err, clientID)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置心跳
|
||||
conn.SetPongHandler(func(string) error {
|
||||
conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
return nil
|
||||
})
|
||||
|
||||
// 保持连接活跃
|
||||
for {
|
||||
messageType, message, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
|
||||
log.Printf("❌ 连接意外断开: %v | ClientID=%s", err, clientID)
|
||||
} else {
|
||||
log.Printf("⚠️ 连接正常关闭: ClientID=%s", clientID)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// 只处理文本消息
|
||||
if messageType == websocket.TextMessage {
|
||||
go handleClientMessage(clientID, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 处理客户端消息
|
||||
func handleClientMessage(senderID string, message []byte) {
|
||||
log.Printf("📥 收到客户端消息: SenderID=%s | Size=%d bytes", senderID, len(message))
|
||||
|
||||
// 尝试解析为发送消息请求
|
||||
var payload SendMessagePayload
|
||||
if err := json.Unmarshal(message, &payload); err == nil && payload.RequestType != "" {
|
||||
log.Printf("📦 解析JSON消息成功: Type=%s", payload.RequestType)
|
||||
|
||||
// 处理绑定请求
|
||||
if payload.RequestType == "bind" && payload.SenderUserID != "" {
|
||||
log.Printf("🔗 处理绑定请求: ClientID=%s -> UserID=%s", senderID, payload.SenderUserID)
|
||||
if err := bindClientToUser(senderID, payload.SenderUserID); err != nil {
|
||||
log.Printf("❌ 绑定失败: %v", err)
|
||||
} else {
|
||||
log.Printf("✅ 绑定成功: ClientID=%s -> UserID=%s", senderID, payload.SenderUserID)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// 处理发送消息请求
|
||||
if payload.RequestType == "send_message" {
|
||||
// 如果指定了目标clientid,则直接发送
|
||||
if payload.TargetClientID != "" {
|
||||
log.Printf("📨 处理客户端发起的发送请求: TargetID=%s | MsgType=%d",
|
||||
payload.TargetClientID, payload.MessageType)
|
||||
|
||||
// 构建客户端消息结构
|
||||
clientMsg := ClientReceivedMessage{
|
||||
SenderID: senderID,
|
||||
ReceiverID: payload.TargetClientID,
|
||||
SenderUserID: payload.SenderUserID,
|
||||
ReceiverUserID: payload.ReceiverUserID,
|
||||
MessageType: payload.MessageType,
|
||||
Content: payload.MessageContent,
|
||||
SendTime: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
// 发送消息
|
||||
sendMessageToClient(payload.TargetClientID, clientMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// 如果指定了接收用户ID,则通过用户ID发送
|
||||
if payload.ReceiverUserID != "" {
|
||||
log.Printf("📨 处理客户端发起的用户发送请求: ReceiverUserID=%s | MsgType=%d",
|
||||
payload.ReceiverUserID, payload.MessageType)
|
||||
|
||||
// 构建客户端消息结构
|
||||
clientMsg := ClientReceivedMessage{
|
||||
SenderID: senderID,
|
||||
ReceiverID: "", // 通过userID发送,留空
|
||||
SenderUserID: payload.SenderUserID,
|
||||
ReceiverUserID: payload.ReceiverUserID,
|
||||
MessageType: payload.MessageType,
|
||||
Content: payload.MessageContent,
|
||||
SendTime: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
// 通过用户ID发送消息
|
||||
sendMessageToUser(payload.ReceiverUserID, clientMsg)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试解析为已封装的消息结构
|
||||
var clientMsg ClientReceivedMessage
|
||||
if err := json.Unmarshal(message, &clientMsg); err == nil && clientMsg.ReceiverID != "" {
|
||||
log.Printf("📨 处理客户端封装消息: TargetID=%s | MsgType=%d",
|
||||
clientMsg.ReceiverID, clientMsg.MessageType)
|
||||
|
||||
// 设置发送者ID(避免客户端冒充)
|
||||
clientMsg.SenderID = senderID
|
||||
|
||||
// 发送消息
|
||||
sendMessageToClient(clientMsg.ReceiverID, clientMsg)
|
||||
return
|
||||
}
|
||||
|
||||
// 无法识别的消息格式
|
||||
log.Printf("⚠️ 无法识别的消息格式: Size=%d bytes | Message=%s", len(message), string(message))
|
||||
}
|
||||
|
||||
// 消息发送处理(HTTP API)- 通过客户端ID发送
|
||||
func sendMessageHandler(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
var payload SendMessagePayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
log.Printf("⚠️ 无效的JSON请求格式: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的JSON格式"})
|
||||
return
|
||||
}
|
||||
|
||||
if payload.RequestType == "" || (payload.TargetClientID == "" && payload.ReceiverUserID == "") ||
|
||||
payload.SenderUserID == "" || payload.ReceiverUserID == "" {
|
||||
log.Printf("⚠️ 缺少必要参数: request_type=%s target_client_id=%s receiver_user_id=%s sender_user_id=%s receiver_user_id=%s",
|
||||
payload.RequestType, payload.TargetClientID, payload.ReceiverUserID, payload.SenderUserID, payload.ReceiverUserID)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少必要参数"})
|
||||
return
|
||||
}
|
||||
|
||||
// 只处理发送消息请求
|
||||
if payload.RequestType == "send_message" {
|
||||
log.Printf("📤 处理API发送请求: SenderUser=%s | MsgType=%d",
|
||||
payload.SenderUserID, payload.MessageType)
|
||||
|
||||
// 构建客户端消息结构
|
||||
clientMsg := ClientReceivedMessage{
|
||||
SenderID: "system", // API消息标记为系统发送
|
||||
ReceiverID: payload.TargetClientID,
|
||||
SenderUserID: payload.SenderUserID,
|
||||
ReceiverUserID: payload.ReceiverUserID,
|
||||
MessageType: payload.MessageType,
|
||||
Content: payload.MessageContent,
|
||||
SendTime: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
var result string
|
||||
var sendErr error
|
||||
|
||||
// 根据目标类型发送
|
||||
if payload.TargetClientID != "" {
|
||||
log.Printf("🎯 目标类型: ClientID | Target=%s", payload.TargetClientID)
|
||||
sendErr = sendMessageToClient(payload.TargetClientID, clientMsg)
|
||||
result = fmt.Sprintf("消息已发送到ClientID: %s", payload.TargetClientID)
|
||||
} else if payload.ReceiverUserID != "" {
|
||||
log.Printf("🎯 目标类型: UserID | ReceiverUser=%s", payload.ReceiverUserID)
|
||||
sendErr = sendMessageToUser(payload.ReceiverUserID, clientMsg)
|
||||
result = fmt.Sprintf("消息已发送到UserID: %s", payload.ReceiverUserID)
|
||||
} else {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "必须指定目标客户端ID或用户ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if sendErr != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": sendErr.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "success", "message": result})
|
||||
log.Printf("✅ API请求完成: Duration=%s", time.Since(start))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的request_type"})
|
||||
}
|
||||
|
||||
// 用户绑定处理
|
||||
func bindHandler(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
var req BindRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
log.Printf("⚠️ 无效的绑定请求格式: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的JSON格式"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.UserID == "" || req.ClientID == "" {
|
||||
log.Printf("⚠️ 缺少必要参数: user_id=%s client_id=%s", req.UserID, req.ClientID)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "user_id和client_id不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("🔗 处理用户绑定请求: UserID=%s ClientID=%s", req.UserID, req.ClientID)
|
||||
|
||||
// 执行绑定
|
||||
if err := bindClientToUser(req.ClientID, req.UserID); err != nil {
|
||||
log.Printf("❌ 绑定失败: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "success",
|
||||
"message": fmt.Sprintf("绑定成功: ClientID %s -> UserID %s", req.ClientID, req.UserID),
|
||||
})
|
||||
|
||||
log.Printf("✅ 绑定请求完成: UserID=%s ClientID=%s | Duration=%s",
|
||||
req.UserID, req.ClientID, time.Since(start))
|
||||
}
|
||||
|
||||
// 通过用户ID发送消息处理(新增独立接口)
|
||||
func sendToUserHandler(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
var payload SendToUserPayload
|
||||
if err := c.ShouldBindJSON(&payload); err != nil {
|
||||
log.Printf("⚠️ 无效的JSON请求格式: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的JSON格式"})
|
||||
return
|
||||
}
|
||||
|
||||
if payload.ReceiverUserID == "" || payload.SenderUserID == "" {
|
||||
log.Printf("⚠️ 缺少必要参数: receiver_user_id=%s sender_user_id=%s",
|
||||
payload.ReceiverUserID, payload.SenderUserID)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "缺少接收方或发送方用户ID"})
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("📤 处理API用户发送请求: SenderUser=%s → ReceiverUser=%s | MsgType=%d",
|
||||
payload.SenderUserID, payload.ReceiverUserID, payload.MessageType)
|
||||
|
||||
// 构建客户端消息结构
|
||||
clientMsg := ClientReceivedMessage{
|
||||
SenderID: "system", // 标记为系统发送
|
||||
ReceiverID: "", // 留空,通过用户ID发送
|
||||
SenderUserID: payload.SenderUserID,
|
||||
ReceiverUserID: payload.ReceiverUserID,
|
||||
MessageType: payload.MessageType,
|
||||
Content: payload.MessageContent,
|
||||
SendTime: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if err := sendMessageToUser(payload.ReceiverUserID, clientMsg); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"status": "success",
|
||||
"message": fmt.Sprintf("消息已发送至用户 %s", payload.ReceiverUserID),
|
||||
})
|
||||
|
||||
log.Printf("✅ API请求完成: Duration=%s", time.Since(start))
|
||||
}
|
||||
|
||||
// 绑定客户端与用户
|
||||
func bindClientToUser(clientID, userID string) error {
|
||||
// 存储 clientid -> userid 映射
|
||||
if err := redisCli.HSet(redisCtx, ClientUserKey, clientID, userID).Err(); err != nil {
|
||||
return fmt.Errorf("保存client-user映射失败: %w", err)
|
||||
}
|
||||
|
||||
// 存储 userid -> clientid 映射(使用集合存储用户所有在线的clientID)
|
||||
userClientKey := fmt.Sprintf("%s:%s", UserClientKey, userID)
|
||||
if err := redisCli.SAdd(redisCtx, userClientKey, clientID).Err(); err != nil {
|
||||
return fmt.Errorf("保存user-client映射失败: %w", err)
|
||||
}
|
||||
|
||||
// 设置过期时间(防止无效数据堆积)
|
||||
expiration := 24 * time.Hour
|
||||
if err := redisCli.Expire(redisCtx, userClientKey, expiration).Err(); err != nil {
|
||||
log.Printf("⚠️ 设置过期时间失败: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("🔗 用户绑定成功: ClientID=%s → UserID=%s", clientID, userID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 通过用户ID发送消息
|
||||
func sendMessageToUser(userID string, msg ClientReceivedMessage) error {
|
||||
start := time.Now()
|
||||
log.Printf("👤 通过用户ID发送消息: UserID=%s", userID)
|
||||
|
||||
// 获取用户关联的所有clientID
|
||||
userClientKey := fmt.Sprintf("%s:%s", UserClientKey, userID)
|
||||
clientIDs, err := redisCli.SMembers(redisCtx, userClientKey).Result()
|
||||
if err != nil {
|
||||
return fmt.Errorf("获取用户clientID失败: %w", err)
|
||||
}
|
||||
|
||||
if len(clientIDs) == 0 {
|
||||
return fmt.Errorf("用户未绑定任何客户端")
|
||||
}
|
||||
|
||||
log.Printf("📡 找到 %d 个关联的客户端: UserID=%s", len(clientIDs), userID)
|
||||
|
||||
var successCount, failCount int
|
||||
var lastError error
|
||||
|
||||
for _, clientID := range clientIDs {
|
||||
// 创建消息副本并设置目标clientID
|
||||
targetMsg := msg
|
||||
targetMsg.ReceiverID = clientID
|
||||
|
||||
if err := sendMessageToClient(clientID, targetMsg); err != nil {
|
||||
log.Printf("❌ 发送消息到客户端失败: ClientID=%s | %v", clientID, err)
|
||||
failCount++
|
||||
lastError = err
|
||||
} else {
|
||||
successCount++
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("📬 消息发送完成: 成功 %d, 失败 %d | UserID=%s | Duration=%s",
|
||||
successCount, failCount, userID, time.Since(start))
|
||||
|
||||
if failCount > 0 {
|
||||
return fmt.Errorf("部分消息发送失败,最后错误: %w", lastError)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 发送消息给客户端(核心函数)
|
||||
func sendMessageToClient(clientID string, msg ClientReceivedMessage) error {
|
||||
start := time.Now()
|
||||
|
||||
// 序列化客户端消息
|
||||
msgJSON, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
log.Printf("❌ 消息序列化失败: %v", err)
|
||||
return fmt.Errorf("内部错误")
|
||||
}
|
||||
|
||||
// 检查目标客户端是否在当前节点
|
||||
if conn := getClient(clientID); conn != nil {
|
||||
log.Printf("📤 向本地客户端发送消息: ClientID=%s | MsgType=%d | Size=%d bytes",
|
||||
clientID, msg.MessageType, len(msgJSON))
|
||||
|
||||
if err := conn.WriteMessage(websocket.TextMessage, msgJSON); err != nil {
|
||||
log.Printf("❌ 发送消息失败: %v | ClientID=%s", err, clientID)
|
||||
removeClient(clientID) // 移除失效连接
|
||||
return fmt.Errorf("发送消息失败")
|
||||
}
|
||||
|
||||
log.Printf("✅ 消息成功发送到本地客户端: ClientID=%s | Duration=%s",
|
||||
clientID, time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
// 如果目标客户端不在当前节点,则通过Redis转发
|
||||
log.Printf("🌐 向远程节点转发消息: ClientID=%s", clientID)
|
||||
|
||||
redisMsg := RedisMessage{
|
||||
SenderNodeID: nodeID,
|
||||
ClientID: clientID,
|
||||
Message: string(msgJSON), // 原始JSON字符串
|
||||
}
|
||||
|
||||
redisMsgJSON, err := json.Marshal(redisMsg)
|
||||
if err != nil {
|
||||
log.Printf("❌ Redis消息序列化失败: %v", err)
|
||||
return fmt.Errorf("内部错误")
|
||||
}
|
||||
|
||||
// 发布到Redis的ws_messages频道
|
||||
if err := redisCli.Publish(redisCtx, "ws_messages", redisMsgJSON).Err(); err != nil {
|
||||
log.Printf("❌ 发布消息到Redis失败: %v", err)
|
||||
return fmt.Errorf("无法转发消息")
|
||||
}
|
||||
|
||||
log.Printf("📡 消息已转发到Redis: ClientID=%s | Size=%d bytes | Duration=%s",
|
||||
clientID, len(redisMsgJSON), time.Since(start))
|
||||
return nil
|
||||
}
|
||||
|
||||
// 订阅Redis消息
|
||||
func subscribeToRedis() {
|
||||
pubsub := redisCli.Subscribe(redisCtx, "ws_messages")
|
||||
defer pubsub.Close()
|
||||
|
||||
ch := pubsub.Channel()
|
||||
|
||||
log.Println("🔔 开始监听Redis消息...")
|
||||
|
||||
for msg := range ch {
|
||||
start := time.Now()
|
||||
var redisMsg RedisMessage
|
||||
|
||||
// 解析Redis消息
|
||||
if err := json.Unmarshal([]byte(msg.Payload), &redisMsg); err != nil {
|
||||
log.Printf("❌ 解析Redis消息失败: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("📥 收到Redis消息: Sender=%s | ClientID=%s | Size=%d bytes",
|
||||
redisMsg.SenderNodeID, redisMsg.ClientID, len(msg.Payload))
|
||||
|
||||
// 如果是本地节点发送的消息,忽略
|
||||
if redisMsg.SenderNodeID == nodeID {
|
||||
log.Println("ℹ️ 忽略本节点转发的消息")
|
||||
continue
|
||||
}
|
||||
|
||||
// 发送给本地客户端
|
||||
if conn := getClient(redisMsg.ClientID); conn != nil {
|
||||
// 直接使用Redis中的原始消息字符串
|
||||
if err := conn.WriteMessage(websocket.TextMessage, []byte(redisMsg.Message)); err != nil {
|
||||
log.Printf("❌ 处理Redis消息失败: %v | ClientID=%s", err, redisMsg.ClientID)
|
||||
removeClient(redisMsg.ClientID)
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("✅ Redis消息已处理: ClientID=%s | Duration=%s",
|
||||
redisMsg.ClientID, time.Since(start))
|
||||
} else {
|
||||
log.Printf("⚠️ 目标客户端不在本节点: ClientID=%s", redisMsg.ClientID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 生成客户端ID (格式: <节点ID>-<UUID>)
|
||||
func generateClientID() string {
|
||||
return fmt.Sprintf("%s-%s", nodeID, uuid.New().String())
|
||||
}
|
||||
|
||||
// 添加客户端到映射
|
||||
func addClient(clientID string, conn *websocket.Conn) {
|
||||
clientsMux.Lock()
|
||||
defer clientsMux.Unlock()
|
||||
clients[clientID] = conn
|
||||
log.Printf("📌 添加客户端到连接池: ClientID=%s | 当前连接数=%d",
|
||||
clientID, len(clients))
|
||||
}
|
||||
|
||||
// 从映射中移除客户端
|
||||
func removeClient(clientID string) {
|
||||
clientsMux.Lock()
|
||||
defer clientsMux.Unlock()
|
||||
|
||||
if _, exists := clients[clientID]; !exists {
|
||||
return
|
||||
}
|
||||
|
||||
delete(clients, clientID)
|
||||
log.Printf("🗑️ 从连接池移除客户端: ClientID=%s | 当前连接数=%d",
|
||||
clientID, len(clients))
|
||||
|
||||
// 从Redis中移除clientid的绑定信息
|
||||
// 注意:这里只移除clientid->userid映射,userid->clientid映射在过期时会自动清理
|
||||
if err := redisCli.HDel(redisCtx, ClientUserKey, clientID).Err(); err != nil {
|
||||
log.Printf("⚠️ 删除client_user_mapping失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 获取客户端连接
|
||||
func getClient(clientID string) *websocket.Conn {
|
||||
clientsMux.RLock()
|
||||
defer clientsMux.RUnlock()
|
||||
return clients[clientID]
|
||||
}
|
||||
|
||||
// 获取环境变量值,如果不存在则使用默认值
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
Reference in New Issue
Block a user