init
This commit is contained in:
44
cmd/server/main.go
Normal file
44
cmd/server/main.go
Normal file
@@ -0,0 +1,44 @@
|
||||
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))
|
||||
}
|
||||
Reference in New Issue
Block a user