-
Notifications
You must be signed in to change notification settings - Fork 1
/
run.go
59 lines (47 loc) · 1.16 KB
/
run.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
package web
import (
"context"
"errors"
"log/slog"
"net/http"
"time"
)
func (app *Application) Run(ctx context.Context, addr string) error {
srv := http.Server{
Addr: addr,
Handler: app.Router(),
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
// start a goro to watch for stop signal (context cancelled)
stopError := make(chan error)
go func() {
<-ctx.Done()
// give the web server 5 seconds to shutdown gracefully
timeout, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
slog.Info("stopping web server")
// disable keepalives and shutdown gracefully
srv.SetKeepAlivesEnabled(false)
err := srv.Shutdown(timeout)
if err != nil {
stopError <- err
}
close(stopError)
}()
slog.Info("starting web server", "addr", srv.Addr)
// listen and serve forever
// ignore http.ErrServerClosed (expected upon stop)
err := srv.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return err
}
// check for errors that arose while stopping
err = <-stopError
if err != nil {
return err
}
slog.Info("stopped web server")
return nil
}