-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
79 lines (62 loc) · 1.3 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
package faker
import (
"context"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
// Server defines server block
type Server struct {
*http.Server
router *mux.Router
}
// Open starts the server
func (s *Server) Open() error {
hn := s.Prepare()
s.Handler = hn
log.Println("Starting Server At:", s.Addr)
return s.ListenAndServe()
}
// Prepare binds the server with Negroni Middlewares
func (s *Server) Prepare() http.Handler {
ng := negroni.New()
ng.Use(negroni.NewRecovery())
ng.Use(negroni.NewLogger())
ng.UseHandler(s.router)
return ng
}
// Close shuts down the server
func (s *Server) Close() error {
ctx, cancel := context.WithTimeout(
context.Background(), 100*time.Second,
)
defer cancel()
return s.Shutdown(ctx)
}
// Handle provides utility method to handle request
func (s *Server) Handle(
path string,
handler http.HandlerFunc,
method []string,
mustParams []Pair,
) {
// Handle the reuquest using router
r := s.router.HandleFunc(path, handler).Methods(method...)
for _, pr := range mustParams {
r.Queries(pr.Key(), pr.Value())
}
}
// NewServer returns the server object
func NewServer(host, port string) *Server {
if port == "" {
port = "8080"
}
return &Server{
&http.Server{
Addr: host + ":" + port,
},
mux.NewRouter(),
}
}