-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
65 lines (58 loc) · 1.67 KB
/
Copy pathserver.go
File metadata and controls
65 lines (58 loc) · 1.67 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
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func (app *application) serve() error {
srv := &http.Server{
Addr: fmt.Sprintf(":%d", app.config.port),
Handler: app.routes(),
IdleTimeout: time.Minute,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
ErrorLog: slog.NewLogLogger(app.logger.Handler(), slog.LevelError),
}
shutdownError := make(chan error)
go func() {
// We use a buffered channel because signal.Notify sends signals asynchronously.
// Unbuffered channels do not store values — they require a receiver to be ready
// at the exact same time the value is sent.
//
// If we used an unbuffered channel, and a signal arrived before our goroutine
// started receiving from the channel, the signal delivery could block or be missed.
//
// A buffered channel (size 1) allows the signal to be stored temporarily until
// our goroutine reads it.
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
s := <-quit
app.logger.Info("caught signal", "signal", s.String())
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err := srv.Shutdown(ctx)
if err != nil {
shutdownError <- err
}
app.logger.Info("completing background tasks", "addr", srv.Addr)
app.wg.Wait()
shutdownError <- nil
}()
app.logger.Info("starting server", "addr", srv.Addr, "env", app.config.env)
err := srv.ListenAndServe()
if !errors.Is(err, http.ErrServerClosed) {
return err
}
err = <-shutdownError
if err != nil {
return err
}
app.logger.Info("stopped server", "addr", srv.Addr)
return nil
}