/
main.go
91 lines (75 loc) · 2.44 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
package main
import (
"context"
"flag"
"io/ioutil"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/mux"
)
// Main function
func main() {
// Setup Logger
Init(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)
var dir string
var wait time.Duration
flag.DurationVar(&wait, "graceful-timeout", time.Second*15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
flag.Parse()
// Init router
r := mux.NewRouter()
// Log endpoints Method + URI
r.Use(loggingMiddleware)
// Hardcoded data - @todo: add database
books = append(books, Book{ID: "1", Isbn: "438227", Title: "Book One", Author: &Author{Firstname: "John", Lastname: "Doe"}})
books = append(books, Book{ID: "2", Isbn: "454555", Title: "Book Two", Author: &Author{Firstname: "Steve", Lastname: "Smith"}})
// Route handles & endpoints
CreateRoutes(r, AllRoutes[:], BaseURL)
// This will serve files under http://localhost:8000/static/<filename>
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
// Walk all the routes
err := r.Walk(RouteWalker)
if err != nil {
Error.Println(err)
}
// Start server
srv := &http.Server{
Handler: r,
Addr: "127.0.0.1:8000",
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Run our server in a goroutine so that it doesn't block.
go func() {
if err := srv.ListenAndServe(); err != nil {
Error.Fatal(err)
}
}()
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
Info.Println("shutting down")
os.Exit(0)
}
// Request sample
// {
// "isbn":"4545454",
// "title":"Book Three",
// "author":{"firstname":"Harry","lastname":"White"}
// }