-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (57 loc) · 1.54 KB
/
main.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
package main
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
"github.com/maximepeschard/statuscode/handler"
"github.com/maximepeschard/statuscode/middleware"
"github.com/maximepeschard/statuscode/status"
"github.com/rs/zerolog/log"
)
const defaultPort string = "8080"
func main() {
port := os.Getenv("PORT")
if port == "" {
log.Warn().Msg("no $PORT, using default port")
port = defaultPort
}
if err := status.Init("data.toml"); err != nil {
log.Fatal().Err(err).Msg("failed to initialize")
}
router := routes()
router.Use(middleware.Logging)
server := &http.Server{
Addr: ":" + port,
Handler: router,
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
}
// Server runs in a goroutine so that it does not block.
go func() {
log.Info().Str("addr", server.Addr).Msg("starting server")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatal().Err(err).Send()
}
}()
// We handle graceful shutdowns for SIGINT and SIGTERM.
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
<-quit
log.Info().Msg("shutting down server")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatal().Err(err).Send()
}
}
func routes() *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/", handler.ListStatus)
router.HandleFunc("/{code}", handler.GetStatus)
return router
}