69 lines
1.3 KiB
Go
69 lines
1.3 KiB
Go
package router
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
|
|
"backend/gateway/internal/service"
|
|
"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
|
|
userService *service.UserService
|
|
}
|
|
|
|
func NewRouter(hub *ws.Hub, userService *service.UserService) *Router {
|
|
return &Router{
|
|
hub: hub,
|
|
userService: userService,
|
|
}
|
|
}
|
|
|
|
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"}`))
|
|
}
|