-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.go
106 lines (85 loc) · 2.44 KB
/
app.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
package main
import (
"context"
"fmt"
"github.com/amirrezam75/go-router"
m "github.com/amirrezam75/go-router/middlewares"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
"net/http"
"os"
"skullking/handlers"
"skullking/middlewares"
"skullking/services"
"time"
)
func initBroker() *redis.Client {
return redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", os.Getenv("BROKER_REDIS_HOST"), os.Getenv("BROKER_REDIS_PORT")),
Password: os.Getenv("BROKER_REDIS_PASSWORD"),
DB: 0,
})
}
func initDatabase() (*mongo.Client, context.CancelFunc, func()) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
var mongoURI = fmt.Sprintf("mongodb://%s:%d", os.Getenv("MONGODB_HOST"), 27017)
var credentials = options.Credential{
AuthSource: os.Getenv("MONGODB_AUTH_SOURCE"),
Username: os.Getenv("MONGODB_USERNAME"),
Password: os.Getenv("MONGODB_PASSWORD"),
}
client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI).SetAuth(credentials))
var disconnect = func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}
err = client.Ping(ctx, readpref.Primary())
if err != nil {
panic(err)
}
return client, cancel, disconnect
}
func loadEnvironments() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
}
func setupRoutes(
gameHandler *handlers.GameHandler,
userService services.UserService,
) *router.Router {
var rateLimiterLogger = func(identifier, url string) {
services.LogService{}.Info(map[string]string{
"message": "Too many requests.",
"identifier": identifier,
"url": url,
})
}
var rateLimiterConfig = m.RateLimiterConfig{
Duration: time.Minute,
Limit: 10,
Extractor: func(r *http.Request) string {
var user = services.ContextService{}.GetUser(r.Context())
if user == nil {
return r.RemoteAddr
}
return user.Id
},
}
var rateLimiterMiddleware = m.NewRateLimiterMiddleware(rateLimiterConfig, rateLimiterLogger)
var authMiddleware = middlewares.Authenticate{UserService: userService}
r := router.NewRouter()
r.Middleware(middlewares.CorsPolicy{})
r.Post("/games", gameHandler.Create).
Middleware(authMiddleware).
Middleware(rateLimiterMiddleware)
r.Get("/games/join", gameHandler.Join)
r.Get("/games/cards", gameHandler.Cards)
return r
}