-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
65 lines (50 loc) · 1.44 KB
/
Copy pathapp.go
File metadata and controls
65 lines (50 loc) · 1.44 KB
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 (
"log"
"flag"
"net/http"
"context"
"os"
"os/signal"
"time"
"syscall"
"github.com/alvintzz/GoGoGo/thisapp"
)
func PongHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pongpongpong"))
}
func main() {
var environment = flag.String("env", "development", "Set Environment of apps. Default is development.")
var configTest = flag.Bool("test", false, "config test")
flag.Parse()
thisapp := thisapp.NewAppModule(*environment)
if *configTest {
os.Exit(0)
}
//Create a mux for routing incoming requests
mux := http.NewServeMux()
mux.HandleFunc("/ping", PongHandler)
thisapp.InitHandlers(mux)
//Create server to serve all incoming request with registered mux
server := &http.Server{
Addr: ":8080",
Handler: mux,
}
//Register stop signal and channel that wait for the signal. If it get the signal,
//then it will be inserted into the channel
stop := make(chan os.Signal)
signal.Notify(stop, os.Interrupt)
signal.Notify(stop, syscall.SIGTERM)
signal.Notify(stop, syscall.SIGINT)
//Run the API using go func while the channel waiting for signal
go func() {
log.Printf("Listening to port %s", ":8080")
log.Fatal(server.ListenAndServe())
}()
<-stop
//The apps will go here only if there STOP signal like ctrl+c or log.Fatal
log.Print("Shutting down server...")
ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
server.Shutdown(ctx)
log.Print("Server gracefully stopped")
}