-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
57 lines (46 loc) · 1.04 KB
/
server.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
package server
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
type Config struct {
Addr string
}
// Server implements a graceful HTTP server.
type Server struct {
server *http.Server
done chan error
}
func New(handler http.Handler, config Config) *Server {
return &Server{
server: &http.Server{
Addr: config.Addr,
Handler: handler,
ReadTimeout: 2 * time.Second,
WriteTimeout: 2 * time.Second,
IdleTimeout: 2 * time.Second,
},
done: make(chan error, 1),
}
}
// Serve starts the HTTP server and serves requests until SIGINT or SIGTERM.
func (s *Server) Serve() error {
go s.shutdownSignal()
err := s.server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
return err
}
return <-s.done
}
func (s *Server) shutdownSignal() {
notifier := make(chan os.Signal, 1)
signal.Notify(notifier, os.Interrupt, syscall.SIGTERM)
<-notifier
ctx, cancel := context.WithTimeout(context.Background(), s.server.WriteTimeout)
defer cancel()
s.done <- s.server.Shutdown(ctx)
}