-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (74 loc) · 1.91 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
package main
import (
"file-management-service/config"
"file-management-service/pkg/cache"
"file-management-service/routes"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// Global variable to hold the configuration
var AppConfig *config.Config
func getPort() string {
port := os.Getenv("PORT")
if port == "" {
port = ":8080"
} else {
port = ":" + port
}
return port
}
func main() {
e := echo.New()
// load .env file
err := godotenv.Load(".env")
if err != nil {
fmt.Println("Error loading environment variables")
}
log.SetOutput(os.Stderr)
// Apply rate limiter middleware
rateLimiterConfig := middleware.RateLimiterConfig{
Skipper: middleware.DefaultSkipper,
Store: middleware.NewRateLimiterMemoryStoreWithConfig(
middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute},
),
IdentifierExtractor: func(ctx echo.Context) (string, error) {
id := ctx.RealIP()
return id, nil
},
ErrorHandler: func(context echo.Context, err error) error {
return context.JSON(http.StatusForbidden, nil)
},
DenyHandler: func(context echo.Context, identifier string, err error) error {
return context.JSON(http.StatusTooManyRequests, nil)
},
}
// Apply rate limiter middleware
e.Use(middleware.RateLimiterWithConfig(rateLimiterConfig))
// Apply CORS middleware
e.Use(middleware.CORS())
config, err := config.LoadConfig()
if err != nil {
log.Fatalf("Failed to load configuration: %s", err)
}
// Assign the configuration to the global variable
AppConfig = config
cache := cache.NewURLCache()
// spawn a goroutine to clear the cache every 5 minutes
go func() {
for {
time.Sleep(5 * time.Minute)
cache.Clear()
}
}()
// Register routes
routes.RegisterRoutes(e, AppConfig, cache)
// Start the server
e.Start(getPort())
log.Println("Server Started!!!")
}