-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
65 lines (52 loc) · 1.44 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
58
59
60
61
62
63
64
65
// server starts an HTTP Server to run the application
package server
import (
"context"
"log"
"net/http"
"time"
"github.com/go-playground/errors/v5"
"github.com/jtwatson/shutdown"
)
const shutdownHammer = time.Second * 5
// Server contains an HTTP Server for running the AppServer
type Server struct {
srv *http.Server
}
// New configures and returns a Server
func New(addr string) *Server {
return &Server{
srv: &http.Server{
Addr: addr,
ReadHeaderTimeout: 60 * time.Second,
},
}
}
// Start starts up an HTTP Server with appServer as its handler.
func (s *Server) Start(ctx context.Context, handler http.Handler) error {
// Capture interrupts so we can handle them gracefully.
ctx, cancel := shutdown.CaptureInterrupts(ctx)
log.Printf("Starting Server at %s", s.srv.Addr)
defer log.Print("Server Exited")
errChan := make(chan error, 1)
go func() {
defer cancel()
defer close(errChan)
s.srv.Handler = handler
if err := s.srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errChan <- errors.Wrap(err, "http.Server shutdown abnormally")
}
}()
<-ctx.Done()
select {
case err := <-errChan:
return err
default:
}
ctxShutDown, cancelShutDown := context.WithTimeout(context.Background(), shutdownHammer)
defer cancelShutDown()
if err := s.srv.Shutdown(ctxShutDown); err != nil {
return errors.Wrap(err, "http.Server.Shutdown(): didn't shutdown gracefully")
}
return nil
}