/
router.go
213 lines (177 loc) · 6.95 KB
/
router.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package server
// Code auto-generated. Do not edit.
import (
"compress/gzip"
"context"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"path"
"syscall"
"time"
"github.com/Clever/go-process-metrics/metrics"
"github.com/Clever/wag/samples/v8/gen-go/tracing"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/kardianos/osext"
"gopkg.in/Clever/kayvee-go.v6/logger"
kvMiddleware "gopkg.in/Clever/kayvee-go.v6/middleware"
)
// Server defines a HTTP server that implements the Controller interface.
type Server struct {
// Handler should generally not be changed. It exposed to make testing easier.
Handler http.Handler
addr string
l logger.KayveeLogger
config serverConfig
}
type serverConfig struct {
compressionLevel int
}
func CompressionLevel(level int) func(*serverConfig) {
return func(c *serverConfig) {
c.compressionLevel = level
}
}
// Serve starts the server. It will return if an error occurs.
func (s *Server) Serve() error {
isLocal := os.Getenv("_IS_LOCAL") == "true"
if !isLocal {
go startLoggingProcessMetrics()
}
go func() {
// This should never return. Listen on the pprof port
log.Printf("PProf server crashed: %s", http.ListenAndServe("localhost:6060", nil))
}()
dir, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
if err := logger.SetGlobalRouting(path.Join(dir, "kvconfig.yml")); err != nil {
s.l.Info("please provide a kvconfig.yml file to enable app log routing")
}
s.l.Counter("server-started")
// Give the sever 30 seconds to shut down
server := &http.Server{
Addr: s.addr,
Handler: s.Handler,
IdleTimeout: 3 * time.Minute,
}
server.SetKeepAlivesEnabled(true)
// Give the server 30 seconds to shut down gracefully after it receives a signal
shutdown := make(chan struct{})
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Signal(syscall.SIGTERM))
sig := <-c
s.l.InfoD("shutdown-initiated", logger.M{"signal": sig.String()})
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
defer close(shutdown)
if err := server.Shutdown(ctx); err != nil {
s.l.CriticalD("error-during-shutdown", logger.M{"error": err.Error()})
}
}()
if err := server.ListenAndServe(); err != http.ErrServerClosed {
return err
}
// ensure we wait for graceful shutdown
<-shutdown
return nil
}
type handler struct {
Controller
}
func startLoggingProcessMetrics() {
metrics.Log("swagger-test", 1*time.Minute)
}
func withMiddleware(serviceName string, router http.Handler, m []func(http.Handler) http.Handler, config serverConfig) http.Handler {
handler := router
// compress everything
handler = handlers.CompressHandlerLevel(handler, config.compressionLevel)
// Wrap the middleware in the opposite order specified so that when called then run
// in the order specified
for i := len(m) - 1; i >= 0; i-- {
handler = m[i](handler)
}
handler = PanicMiddleware(handler)
// Logging middleware comes last, i.e. will be run first.
// This makes it so that other middleware has access to the logger
// that kvMiddleware injects into the request context.
handler = kvMiddleware.New(handler, serviceName)
return handler
}
// New returns a Server that implements the Controller interface. It will start when "Serve" is called.
func New(c Controller, addr string, options ...func(*serverConfig)) *Server {
return NewWithMiddleware(c, addr, []func(http.Handler) http.Handler{}, options...)
}
// NewRouter returns a mux.Router with no middleware. This is so we can attach additional routes to the
// router if necessary
func NewRouter(c Controller) *mux.Router {
return newRouter(c)
}
func newRouter(c Controller) *mux.Router {
router := mux.NewRouter()
router.Use(tracing.MuxServerMiddleware("swagger-test"))
h := handler{Controller: c}
router.Methods("GET").Path("/v1/authors").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "getAuthors")
h.GetAuthorsHandler(r.Context(), w, r)
})
router.Methods("PUT").Path("/v1/authors").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "getAuthorsWithPut")
h.GetAuthorsWithPutHandler(r.Context(), w, r)
})
router.Methods("GET").Path("/v1/books").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "getBooks")
h.GetBooksHandler(r.Context(), w, r)
})
router.Methods("POST").Path("/v1/books").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "createBook")
h.CreateBookHandler(r.Context(), w, r)
})
router.Methods("PUT").Path("/v1/books").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "putBook")
h.PutBookHandler(r.Context(), w, r)
})
router.Methods("GET").Path("/v1/books/{book_id}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "getBookByID")
h.GetBookByIDHandler(r.Context(), w, r)
})
router.Methods("GET").Path("/v1/books2/{id}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "getBookByID2")
h.GetBookByID2Handler(r.Context(), w, r)
})
router.Methods("GET").Path("/v1/health/check").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.FromContext(r.Context()).AddContext("op", "healthCheck")
h.HealthCheckHandler(r.Context(), w, r)
})
return router
}
// NewWithMiddleware returns a Server that implemenets the Controller interface. It runs the
// middleware after the built-in middleware (e.g. logging), but before the controller methods.
// The middleware is executed in the order specified. The server will start when "Serve" is called.
func NewWithMiddleware(c Controller, addr string, m []func(http.Handler) http.Handler, options ...func(*serverConfig)) *Server {
router := newRouter(c)
return AttachMiddleware(router, addr, m, options...)
}
// AttachMiddleware attaches the given middleware to the router; this is to be used in conjunction with
// NewServer. It attaches custom middleware passed as arguments as well as the built-in middleware for
// logging, tracing, and handling panics. It should be noted that the built-in middleware executes first
// followed by the passed in middleware (in the order specified).
func AttachMiddleware(router *mux.Router, addr string, m []func(http.Handler) http.Handler, options ...func(*serverConfig)) *Server {
// Set sane defaults, to be overriden by the varargs functions.
// This would probably be better done in NewWithMiddleware, but there are services that call
// AttachMiddleWare directly instead.
config := serverConfig{
compressionLevel: gzip.DefaultCompression,
}
for _, option := range options {
option(&config)
}
l := logger.New("swagger-test")
handler := withMiddleware("swagger-test", router, m, config)
return &Server{Handler: handler, addr: addr, l: l, config: config}
}