-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
90 lines (74 loc) · 1.86 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package msv
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/ribice/msv/middleware/httplog"
"github.com/ribice/msv/middleware/recovery"
"github.com/gorilla/mux"
)
// Server represents http server
type Server struct {
m *mux.Router
*http.Server
}
// New instantiates new http server with logging and recover middleware
func New(prefix string) (*Server, *mux.Router) {
m := mux.NewRouter()
rmw := recovery.New(prefix)
lmw := httplog.New(prefix, "/")
m.Use(rmw.MWFunc, lmw.MWFunc)
port := "8080"
if p, ok := os.LookupEnv("PORT"); ok {
port = p
}
srv := &Server{m: m, Server: &http.Server{
Addr: fmt.Sprintf(":%s", port),
Handler: m,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}}
return srv, srv.m
}
// Start starts the http server
func (s *Server) Start() error {
go func() {
log.Printf("starting server on port%v", s.Addr)
s.ListenAndServe()
}()
// Setting up signal capturing
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
// Waiting for SIGINT (pkill -2)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
return fmt.Errorf("error stopping server: %s", err)
}
log.Print("gracefully stopped server")
return nil
}
// StartTLS starts the https server
func (s *Server) StartTLS(cf, kf string) error {
go func() {
log.Printf("starting server on port%v", s.Addr)
s.ListenAndServeTLS(cf, kf)
}()
// Setting up signal capturing
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
// Waiting for SIGINT (pkill -2)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
return fmt.Errorf("error stopping server: %s", err)
}
log.Print("gracefully stopped server")
return nil
}