-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (60 loc) · 1.55 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
package main
import (
"context"
"errors"
"jsmi-api/db"
"jsmi-api/routes"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
func main() {
// Load configuration
config, err := db.LoadEnvConfig()
if err != nil {
log.Fatalf("failed to load ENV configuration: %v", err)
}
// Migrate the database
migrateCfg := db.MigrateConfig{
DBURL: config.DBURL,
}
if err := db.Migrate(migrateCfg); err != nil {
log.Fatalf("error migrating database: %v", err)
}
// Set up routes and middlewares
handler := routes.SetupRoutes(config)
srv := &http.Server{
Addr: ":8000",
Handler: handler,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
MaxHeaderBytes: 7500,
IdleTimeout: 120 * time.Second,
}
// Use a wait group to manage graceful shutdown
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("listenAndServe(): %v", err)
}
}()
log.Println("server started on :8000")
// Wait for interrupt signal to gracefully shut down the server
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c
// Create a context with a timeout for shutdown
shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelShutdown()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatalf("server shutdown failed: %+v", err)
}
wg.Wait() // Wait for all goroutines to finish before exiting
log.Println("server exited gracefully")
}