-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
45 lines (39 loc) · 806 Bytes
/
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
package main
import (
"context"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"golang.org/x/sync/errgroup"
)
type Server struct {
srv *http.Server
l net.Listener
}
func NewServer(l net.Listener, mux http.Handler) *Server {
return &Server{
srv: &http.Server{Handler: mux},
l: l,
}
}
func (s *Server) Run(ctx context.Context) error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
if err := s.srv.Serve(s.l); err != nil &&
err != http.ErrServerClosed {
log.Printf("failed to close: %+v", err)
return err
}
return nil
})
<-ctx.Done()
if err := s.srv.Shutdown(context.Background()); err != nil {
log.Printf("failed to shutdown: %+v", err)
}
return eg.Wait()
}