-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
server.go
73 lines (60 loc) 路 1.51 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
66
67
68
69
70
71
72
73
// Package http provides HTTP server.
package http
import (
"context"
"fmt"
"net/http"
"time"
log "github.com/sirupsen/logrus"
"github.com/amerkurev/doku/app/docker"
)
// Server is a server for http.
type Server struct {
Address string
Timeouts Timeouts
BasicAuthEnabled bool
BasicAuthAllowed []string
StaticFolder string
UITitle string
UIHeader string
}
// Timeouts consolidate timeouts for both server and transport
type Timeouts struct {
Write time.Duration
Read time.Duration
Idle time.Duration
Shutdown time.Duration
}
// Run creates and starts an HTTP server.
func (s *Server) Run(ctx context.Context, d *docker.Client) error {
router := CreateRouter(ctx, s, d)
httpServer := &http.Server{
Addr: s.Address,
Handler: router,
ReadTimeout: s.Timeouts.Read,
WriteTimeout: s.Timeouts.Write,
IdleTimeout: s.Timeouts.Idle,
}
done := make(chan struct{}, 1)
go func() {
<-ctx.Done()
// shutdown signal with grace period of `shutdownTimeout` seconds
ctx, cancel := context.WithTimeout(context.Background(), s.Timeouts.Shutdown)
defer func() {
cancel()
done <- struct{}{}
}()
err := httpServer.Shutdown(ctx)
if err != nil {
log.WithField("err", err).Error("failed to shut down the http server")
return
}
log.Info("gracefully http server shutdown")
}()
err := httpServer.ListenAndServe()
if err != nil && err == http.ErrServerClosed {
<-done
return nil
}
return fmt.Errorf("http server failed: %w", err)
}