/
server.go
66 lines (52 loc) · 1.37 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
package rest
import (
"net/http"
"github.com/gorilla/mux"
)
// New will create and initialize the server
func New(address string) *Server {
return &Server{
address: address,
handlerGet: &GetHandler{},
handlerList: &ListHandler{},
handlerNotFound: notFoundHandler,
handlerRegister: &RegisterHandler{},
}
}
// Server is the HTTP REST server
type Server struct {
address string
server *http.Server
handlerGet http.Handler
handlerList http.Handler
handlerNotFound http.HandlerFunc
handlerRegister http.Handler
}
// Listen will start a HTTP rest for this service
func (s *Server) Listen(stop <-chan struct{}) {
router := s.buildRouter()
// create the HTTP server
s.server = &http.Server{
Handler: router,
Addr: s.address,
}
// listen for shutdown
go func() {
// wait for shutdown signal
<-stop
_ = s.server.Close()
}()
// start the HTTP server
_ = s.server.ListenAndServe()
}
// configure the endpoints to handlers
func (s *Server) buildRouter() http.Handler {
router := mux.NewRouter()
// map URL endpoints to HTTP handlers
router.Handle("/person/{id}/", s.handlerGet).Methods("GET")
router.Handle("/person/list", s.handlerList).Methods("GET")
router.Handle("/person/register", s.handlerRegister).Methods("POST")
// convert a "catch all" not found handler
router.NotFoundHandler = s.handlerNotFound
return router
}