-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
66 lines (57 loc) · 1.54 KB
/
Copy pathmain.go
File metadata and controls
66 lines (57 loc) · 1.54 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
package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"magic-image/internal/cache"
"magic-image/internal/config"
"magic-image/internal/fetch"
"magic-image/internal/server"
)
func main() {
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
cfg := config.Load()
c := cache.New(cfg.RedisAddr, cfg.RedisPassword, cfg.RedisDB, cfg.CacheTTL)
pingCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := c.Ping(pingCtx); err != nil {
log.Error("redis unreachable", "addr", cfg.RedisAddr, "err", err)
os.Exit(1)
}
defer c.Close()
f := fetch.New(fetch.Options{
Timeout: cfg.FetchTimeout,
MaxBytes: cfg.MaxImageBytes,
AllowPrivate: cfg.AllowPrivate,
AllowedHosts: cfg.AllowedHosts,
})
srv := server.New(cfg, f, c, log)
httpSrv := &http.Server{
Addr: cfg.Addr,
Handler: srv.Routes(),
ReadTimeout: cfg.HTTPTimeout,
WriteTimeout: cfg.HTTPTimeout,
IdleTimeout: 60 * time.Second,
}
go func() {
log.Info("listening", "addr", cfg.Addr)
if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error("server error", "err", err)
os.Exit(1)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
log.Info("shutting down")
shutCtx, shutCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer shutCancel()
if err := httpSrv.Shutdown(shutCtx); err != nil {
log.Error("graceful shutdown failed", "err", err)
}
}