-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
68 lines (59 loc) · 1.65 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
// Copyright (c) 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package server
import (
"context"
"github.com/harunnryd/skeltun/internal/app/handler"
"github.com/harunnryd/skeltun/internal/pkg/http/wrapper"
"log"
"net/http"
"os"
"time"
)
// IServer ...
type IServer interface {
Router(handler handler.IHandler) (w wrapper.IWrapper)
GetHTTPServer() *http.Server
GracefullShutdown(server *http.Server, logger *log.Logger, quit <-chan os.Signal, done chan<- bool)
}
// Server will create a http.Server from the Go standard library
type Server struct {
ErrorLog *log.Logger
Addr string
Handler handler.IHandler
ReadTimeout time.Duration
WriteTimeout time.Duration
IdleTimeout time.Duration
}
// New ...
func New(opts ...Option) IServer {
srv := new(Server)
for _, opt := range opts {
opt(srv)
}
return srv
}
// GetHTTPServer ...
func (s *Server) GetHTTPServer() *http.Server {
return &http.Server{
ErrorLog: s.ErrorLog,
Addr: s.Addr,
Handler: s.Router(s.Handler),
ReadTimeout: s.ReadTimeout,
WriteTimeout: s.WriteTimeout,
IdleTimeout: s.IdleTimeout,
}
}
// GracefullShutdown ...
func (s *Server) GracefullShutdown(server *http.Server, logger *log.Logger, quit <-chan os.Signal, done chan<- bool) {
<-quit
logger.Println("Server is shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
server.SetKeepAlivesEnabled(false)
if err := server.Shutdown(ctx); err != nil {
logger.Fatalf("Could not gracefully shutdown the server: %v\n", err)
}
close(done)
}