-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (54 loc) · 1.77 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"
muxhandlers "github.com/gorilla/handlers"
"github.com/nicholasjackson/env"
"github.com/sirupsen/logrus"
"net/http"
"os"
"os/signal"
"time"
)
var (
l *logrus.Logger
bindAddress = env.String("BIND_ADDRESS", false, ":9090", "Bind address for the server")
)
func main() {
// Parse the environment vars
env.Parse()
// Create logger(s)
l = logrus.New()
r := CreateRouter()
// Add gorilla CORS handling
headersOk := muxhandlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Origin"})
originsOk := muxhandlers.AllowedOrigins([]string{"*"})
methodsOk := muxhandlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
h := muxhandlers.CORS(headersOk, originsOk, methodsOk)(r)
// Create a new server
s := http.Server{
Addr: *bindAddress, // configure the bind address
Handler: h, // set the default handler
ReadTimeout: 5 * time.Second, // max time to read request from the client
WriteTimeout: 10 * time.Second, // max time to write response to the client
IdleTimeout: 120 * time.Second, // max time for connections using TCP Keep-Alive
}
// Start the server
go func() {
l.Printf("Starting server on %s \n", *bindAddress)
err := s.ListenAndServe()
if err != nil {
l.Printf("Error starting server: %s\n", err)
os.Exit(1)
}
}()
// Trap sigterm or interrupt and gracefully shutdown the server
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
// Block until a signal is received.
sig := <-c
l.Println("Got signal:", sig)
// gracefully shutdown the server, waiting max 30 seconds for current operations to complete
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
s.Shutdown(ctx)
}