-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
107 lines (90 loc) · 2.5 KB
/
main.go
File metadata and controls
107 lines (90 loc) · 2.5 KB
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
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/joho/godotenv"
htmlHandler "antman-proxy/handlers/html"
imageHandler "antman-proxy/handlers/image"
cacheManager "antman-proxy/managers/cache"
imageManager "antman-proxy/managers/image"
"antman-proxy/server"
)
func main() {
err := godotenv.Load(".env")
if err != nil {
// Should check whether this is dev or production environment and log or throw a fatal appropriately.
log.Println("Error loading .env file")
}
// Create context that listens for the interrupt signal from the OS.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
html, err := htmlHandler.NewHandler()
if err != nil {
log.Fatal(err)
}
maxAge, err := strconv.ParseInt(os.Getenv("CACHE_MAX_AGE"), 10, 64)
if err != nil {
log.Fatal(err)
}
cache, err := cacheManager.NewManager(&cacheManager.Config{
CacheDir: os.Getenv("CACHE_DIR"),
MaxAge: maxAge,
})
if err != nil {
log.Fatal(err)
}
allowedDomains := strings.Split(os.Getenv("ALLOWED_DOMAINS"), ",")
imgManager, err := imageManager.NewManager(&imageManager.Config{
AllowedDomains: allowedDomains,
CacheManager: cache,
})
if err != nil {
log.Fatal(err)
}
numWorkers, _ := strconv.Atoi(os.Getenv("NUM_WORKERS"))
image, err := imageHandler.NewHandler(&imageHandler.Config{
ImageManager: imgManager,
WorkerPool: imageHandler.NewWorkerPool(numWorkers),
})
if err != nil {
log.Fatal(err)
}
s := server.NewServer(&server.Config{
HtmlHandler: html,
ImageHandler: image,
CacheManager: cache,
ImageManager: imgManager,
Port: port,
})
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Listen for the interrupt signal.
<-ctx.Done()
// Restore default behavior on the interrupt signal and notify user of shutdown.
stop()
log.Println("shutting down gracefully, press Ctrl+C again to force")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
log.Fatal("Server forced to shutdown: ", err)
}
log.Println("Server exiting")
}