feat: 实现网关服务的长连接功能
This commit is contained in:
62
backend/gateway/internal/router/router.go
Normal file
62
backend/gateway/internal/router/router.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"backend/gateway/internal/ws"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
// 允许所有来源的请求
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
type Router struct {
|
||||
hub *ws.Hub
|
||||
}
|
||||
|
||||
func NewRouter(hub *ws.Hub) *Router {
|
||||
return &Router{
|
||||
hub: hub,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) SetupRoutes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// WebSocket 连接处理
|
||||
mux.HandleFunc("/ws", r.handleWebSocket)
|
||||
|
||||
// 健康检查
|
||||
mux.HandleFunc("/health", r.handleHealth)
|
||||
|
||||
return mux
|
||||
}
|
||||
|
||||
func (r *Router) handleWebSocket(w http.ResponseWriter, req *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, req, nil)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
client := ws.NewClient(r.hub, conn)
|
||||
r.hub.register <- client
|
||||
|
||||
// 启动客户端的读写协程
|
||||
go client.writePump()
|
||||
go client.readPump()
|
||||
}
|
||||
|
||||
func (r *Router) handleHealth(w http.ResponseWriter, req *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"status": "ok"}`))
|
||||
}
|
||||
Reference in New Issue
Block a user