This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
app.go
76 lines (63 loc) · 1.62 KB
/
app.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
package app
import (
"context"
"net/http"
"os"
"time"
"github.com/rs/zerolog"
)
// ScoketTimeout set timeout for HTTP server
const ScoketTimeout = 30 * time.Second
// App is used for keep central location of configuration and resources
type App struct {
Logger *zerolog.Logger
Handler *http.ServeMux
server *http.Server
}
// NewApp initialize App instance
func NewApp() (*App, error) {
// Configuration
addr := ":" + os.Getenv("PORT")
if addr == ":" {
addr = ":8080"
}
mux := http.NewServeMux()
zerolog.TimeFieldFormat = ""
zerolog.SetGlobalLevel(zerolog.DebugLevel)
// To use JSON format output for logs:
// logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
logger := zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
app := &App{
Logger: &logger,
Handler: mux,
server: newHTTPServer(mux, addr),
}
return app, nil
}
// Serve start listen on port for HTTP
func (app *App) Serve() {
app.Logger.Info().Msgf("Listening on http://0.0.0.0%s", app.server.Addr)
err := app.server.ListenAndServe()
if err != nil {
app.Logger.
Fatal().
Err(err).
Msg("HTTPServer crashed")
}
}
// Shutdown gracefully stop HTTP server
func (app *App) Shutdown() {
app.Logger.Info().Msg("Shutting down the server...")
ctx, _ := context.WithTimeout(context.Background(), ScoketTimeout)
app.server.Shutdown(ctx)
app.Logger.Info().Msg("Server stopped")
}
func newHTTPServer(handler http.Handler, addr string) *http.Server {
httpServer := &http.Server{
Handler: handler,
Addr: addr,
ReadTimeout: ScoketTimeout,
WriteTimeout: ScoketTimeout,
}
return httpServer
}