Files
ChatRoom/cmd/server/main.go
2026-02-03 23:45:27 +08:00

45 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"ChatRoom/internal/rabbitmq"
"ChatRoom/internal/ws"
"log"
"net/http"
"os"
"path/filepath"
)
func main() {
// 1. 初始化 RabbitMQ
rabbitmqURL := os.Getenv("RABBITMQ_URL")
if rabbitmqURL == "" {
rabbitmqURL = "amqp://guest:guest@localhost:5672/"
}
rmq, err := rabbitmq.NewClient(rabbitmqURL)
if err != nil {
log.Fatalf("RabbitMQ 连接失败: %v", err)
}
defer rmq.Close()
// 2. WebSocket 路由
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
ws.NewConnection(w, r, rmq) // 传入 RabbitMQ 客户端
})
// 3. 静态文件服务(用于测试前端)
webDir := "./web"
if _, err := os.Stat(webDir); os.IsNotExist(err) {
// 从 cmd/server 目录运行时web 在项目根目录
webDir = filepath.Join("..", "..", "web")
}
http.Handle("/", http.FileServer(http.Dir(webDir)))
// 4. 启动服务
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
log.Printf("服务启动: http://localhost:%s", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}