-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (57 loc) · 1.92 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
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"./handlers"
"github.com/gorilla/mux"
"github.com/nicholasjackson/env"
)
var bindAddress = env.String("BIND_ADDRESS", false, ":9000", "Bind address for the server")
func main() {
env.Parse()
l := log.New(os.Stdout, "products-api", log.LstdFlags)
// create the handlers
ph := handlers.NewProducts(l)
// create a new serve mux and register the handlers
sm := mux.NewRouter()
getRouter := sm.Methods(http.MethodGet).Subrouter()
getRouter.HandleFunc("/", ph.GetProducts)
putRouter := sm.Methods(http.MethodPut).Subrouter()
putRouter.HandleFunc("/{id:[0-9]+}", ph.UpdateProducts)
putRouter.Use(ph.MiddlewareValidateProduct)
postRouter := sm.Methods(http.MethodPost).Subrouter()
postRouter.HandleFunc("/", ph.AddProduct)
postRouter.Use(ph.MiddlewareValidateProduct)
// create a new server
s := http.Server{
Addr: *bindAddress, // configure the bind address
Handler: sm, // set the default handler
ErrorLog: l, // set the logger for the server
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.Println("Starting server on port 9000")
err := s.ListenAndServe()
if err != nil {
l.Printf("Error starting server: %s\n", err)
os.Exit(1)
}
}()
// trap sgterm or interupt and gracefully shitdown the serve
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
// Block until a signal is received.
sig := <-c
log.Println("Got signal:", sig)
// gracefully shotdow the server, waiting max 30 seconds for current operations to complete
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
s.Shutdown(ctx)
}