-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
49 lines (38 loc) · 893 Bytes
/
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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"time"
"github.com/rs/zerolog/log"
"github.com/urfave/negroni"
)
type RouteMapper func(mux *http.ServeMux)
func NewRouter(handlers ...RouteMapper) *negroni.Negroni {
mux := http.NewServeMux()
for _, handler := range handlers {
handler(mux)
}
return negroni.New(
negroni.NewRecovery(),
NewZerologRequestIdMiddleware(),
NewLoggingMiddleware(),
negroni.Wrap(mux),
)
}
func Serve(ctx context.Context, port int, router http.Handler) error {
s := &http.Server{
Handler: router,
Addr: fmt.Sprintf(":%d", port),
}
go func() {
if err := s.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Ctx(ctx).Fatal().Msg(err.Error())
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
return s.Shutdown(shutdownCtx)
}