-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
53 lines (42 loc) · 1.22 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
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/slaven/go-calculator/calcserver"
)
func main() {
log.Println("[Server] Starting http server")
// Create context and listen for the interrupt signal
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
// Create handler
calcHandler := calcserver.Create()
srv := http.Server{
Addr: ":8080",
Handler: calcHandler,
ReadTimeout: time.Duration(30 * time.Second),
WriteTimeout: time.Duration(30 * time.Second),
IdleTimeout: time.Duration(30 * time.Second),
}
// Listen on a different Goroutine to avoid blocking
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("[Server] ListenAndServe: %v", err)
}
}()
// Listen for the interrupt signal
<-ctx.Done()
// Cancel context for the interrupt signal
stop() // TODO: not needed?
log.Println("[Server] Shutting down gracefully, press Ctrl+C again to force")
// Perform server shutdown with timeout
timeoutCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(timeoutCtx); err != nil {
log.Printf("[Server] Shutdown error: %v", err)
}
}