-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
163 lines (135 loc) · 4.22 KB
/
main.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/connerdouglass/livechat-api/models"
"github.com/connerdouglass/livechat-api/services"
v1 "github.com/connerdouglass/livechat-api/v1"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
socketio "github.com/googollee/go-socket.io"
"github.com/googollee/go-socket.io/engineio"
"github.com/googollee/go-socket.io/engineio/transport"
"github.com/googollee/go-socket.io/engineio/transport/polling"
"github.com/googollee/go-socket.io/engineio/transport/websocket"
"github.com/joho/godotenv"
"gorm.io/gorm"
)
func main() {
// Load the .env file
err := godotenv.Load()
if err != nil {
fmt.Println("Error loading .env file: ", err)
}
//================================================================================
// Create the database connection
//================================================================================
// Get the datbase driver for the database string
dbDriver := ParseDatabaseDriver(os.Getenv("DB_URL"))
if dbDriver == nil {
log.Fatalln("Failed to create database driver. Check DB_URL environment variable")
}
// Create the database connection
db, err := gorm.Open(dbDriver, &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
NowFunc: func() time.Time {
return time.Now().UTC()
},
})
if err != nil {
panic("failed to connect database")
}
// Migrate the schema
db.AutoMigrate(
&models.Account{},
&models.Badge{},
&models.BannedWord{},
&models.ChatRoom{},
&models.MutedUser{},
&models.Organization{},
)
//================================================================================
// Setup the WebSockets server
//================================================================================
// Get all of the allowed origins
allowedOrigins := GetAllowedOrigins()
// Create the server
socketIoServer := socketio.NewServer(&engineio.Options{
Transports: []transport.Transport{
&polling.Transport{
CheckOrigin: checkOrigin(allowedOrigins),
},
&websocket.Transport{
CheckOrigin: checkOrigin(allowedOrigins),
},
},
})
go socketIoServer.Serve()
//================================================================================
// Create all the service instances
//================================================================================
chatService := &services.ChatService{
DB: db,
}
socketsService := &services.SocketsService{
Server: socketIoServer,
ChatService: chatService,
}
accountsService := &services.AccountsService{DB: db}
authTokensService := &services.AuthTokensService{
DB: db,
SigningPepper: os.Getenv("AUTH_TOKEN_SIGNING_PEPPER"),
}
// Do some final update on the sockets service
// Needed because it has a circular relationship with other services
socketsService.Setup()
//================================================================================
// Setup the Gin HTTP router
//================================================================================
// Create the Gin router
r := gin.Default()
// Configure CORS for the API
corsCfg := cors.DefaultConfig()
corsCfg.AllowOrigins = GetAllowedOrigins()
corsCfg.AllowCredentials = true
corsCfg.AddAllowHeaders("Accept", "User-Agent", "Authorization")
r.Use(cors.New(corsCfg))
// Create the API instance
api := &v1.Server{
AccountsService: accountsService,
AuthTokensService: authTokensService,
ChatService: chatService,
}
// Mount the API routes
api.Setup(r.Group("v1"))
// Create a mux to serve both the HTTP and Socket.IO servers
mux := http.NewServeMux()
mux.Handle("/socket.io/", socketIoServer)
mux.Handle("/", r)
// Run the server
if err := http.ListenAndServe(":8080", mux); err != nil {
log.Panicln(err)
}
}
// GetAllowedOrigins gets the slice of allowed CORS origins
func GetAllowedOrigins() []string {
// Get the list of origins allowed
env, ok := os.LookupEnv("CORS_ALLOW_ORIGINS")
if !ok {
return []string{}
}
// Create the slice for it
origins := []string{}
// Split up the env value
originsRaw := strings.Split(env, ",")
for _, originRaw := range originsRaw {
origin := strings.TrimSpace(originRaw)
origins = append(origins, origin)
}
// Return the origins slice
return origins
}