-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (49 loc) · 1.26 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
package main
import (
"fmt"
"io"
"net/http"
"os"
"os/signal"
"syscall"
"time"
loggo "github.com/moatorres/go/modules/logger"
"github.com/moatorres/go/modules/utils"
)
// file server
func FileServerHandler() http.Handler {
return http.FileServer(http.Dir("./static"))
}
// logger instance
var logger = loggo.New(loggo.LoggerOptions{
Service: "infrago",
})
// health handler
func healthz(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "OK")
logger.Log(r.Method + " " + r.Host + r.URL.Path)
}
// graceful process
func main() {
port := utils.GetEnvVar("PORT", "3000")
fileServer := FileServerHandler()
serverTimeout := 10
http.Handle("/", fileServer)
http.HandleFunc("/healthz", healthz)
signalsChannel := make(chan os.Signal, 1)
watchedSignals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGINT}
signal.Notify(signalsChannel, watchedSignals...)
go func() {
logger.Log("Server is running at %s", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
logger.Fatal(err)
}
}()
sig := <-signalsChannel
logger.Warn("Caught signal '%v'", sig)
logger.Log("Server will shut down in %s seconds", fmt.Sprint(serverTimeout))
time.Sleep(time.Second * time.Duration(serverTimeout))
logger.Log("Bye 👋")
os.Exit(0)
}