-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
103 lines (83 loc) · 2.28 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"time"
"cartracker.api/common"
"cartracker.api/data"
"cartracker.api/routers"
"cartracker.api/settings"
"github.com/urfave/negroni"
)
// HTMLServer the struct
type HTMLServer struct {
server *http.Server
wg sync.WaitGroup
}
// our main function
func main() {
settings.Init()
common.MongoSession = data.InitMongoSession()
htmlServer := Start(common.ServerCfg)
defer htmlServer.Stop()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt)
<-sigChan
fmt.Println("main : shutting down")
}
// Start launches the HTML Server
func Start(cfg *common.ServerConfig) *HTMLServer {
// Setup Context
_, cancel := context.WithCancel(context.Background())
defer cancel()
// Setup Handlers
router := routers.NewRouter()
n := negroni.Classic() // Includes some default middlewares
n.Use(negroni.NewStatic(http.Dir("/static")))
n.UseHandler(router)
// Create the HTML Server
htmlServer := HTMLServer{
server: &http.Server{
Addr: cfg.Host,
Handler: n,
ReadTimeout: cfg.ReadTimeout * time.Second,
WriteTimeout: cfg.WriteTimeout * time.Second,
MaxHeaderBytes: 1 << 20,
},
}
fmt.Print(cfg.ReadTimeout)
// Add to the WaitGroup for the listener goroutine
htmlServer.wg.Add(1)
// Start the listener
go func() {
fmt.Printf("\nHTMLServer : Service started : Host=%v\n", cfg.Host)
htmlServer.server.ListenAndServe()
htmlServer.wg.Done()
}()
return &htmlServer
}
// Stop turns off the HTML Server
func (htmlServer *HTMLServer) Stop() error {
// Create a context to attempt a graceful 5 second shutdown.
const timeout = 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
fmt.Printf("\nHTMLServer : Service stopping\n")
// Attempt the graceful shutdown by closing the listener
// and completing all inflight requests
if err := htmlServer.server.Shutdown(ctx); err != nil {
// Looks like we timed out on the graceful shutdown. Force close.
if err := htmlServer.server.Close(); err != nil {
fmt.Printf("\nHTMLServer : Service stopping : Error=%v\n", err)
return err
}
}
// Wait for the listener to report that it is closed.
htmlServer.wg.Wait()
fmt.Printf("\nHTMLServer : Stopped\n")
return nil
}