-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
70 lines (60 loc) · 1.42 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"context"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"log"
"messenger/config"
"messenger/handlers"
"messenger/hub"
"messenger/internal/common"
"os"
)
const defaultPort = "8080"
func main() {
appConfig := config.NewFromEnv()
db, err := common.InitDb(appConfig)
if err != nil {
log.Fatalf("Failed to init database: %s", err)
}
defer dbDisconnect(db)
r := gin.Default()
ctx := &common.Context{
Database: db,
}
r.Use(func(c *gin.Context) {
con := context.WithValue(c.Request.Context(), "ctx", ctx)
c.Request = c.Request.WithContext(con)
c.Next()
})
r.Use(cors.Default())
go hub.MainHub.Run()
r.GET("/ws", func(c *gin.Context) {
hub.ServeWs(c, hub.MainHub)
})
// REST
r.POST("/api/message", handlers.SendMessage)
r.POST("/api/register", handlers.Register)
r.POST("/api/join", handlers.Join)
r.POST("/api/leave", handlers.Leave)
// GQL
r.GET("", handlers.PlaygroundHandler())
r.POST("/graph/api", handlers.GraphqlHandler)
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(r.Run(":" + port))
}
func dbDisconnect(dbConn *gorm.DB) {
database, err := dbConn.DB()
if err != nil {
log.Fatalf("Failed to close database connection: %s", err)
}
err = database.Close()
if err != nil {
log.Fatalf("Failed to close database connection: %s", err)
}
}