-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
93 lines (81 loc) · 2.29 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"dev.acorello.it/go/contacts/contact"
http_contact "dev.acorello.it/go/contacts/contact/http"
"dev.acorello.it/go/contacts/public_assets"
)
var repo = contact.NewPopulatedInMemoryContactRepository()
func main() {
mux := http.NewServeMux()
const publicRootPath = "/public/"
mux.HandleFunc(publicRootPath,
LoggingHandler(http.StripPrefix(publicRootPath, public_assets.FileServer())))
contactResourcePaths := http_contact.ResourcePaths{
Root: "/contact/",
Form: "/contact/form",
List: "/contact/list",
Email: "/contact/email",
}
if validatedPaths, err := contactResourcePaths.Validated(); err != nil {
log.Fatal(err)
} else {
contactHandler := http_contact.NewContactHandler(validatedPaths, &repo)
mux.HandleFunc(validatedPaths.Root.String(), LoggingHandler(contactHandler))
homeRedirect := http.RedirectHandler(validatedPaths.List.String(), http.StatusFound)
mux.HandleFunc("/", LoggingHandler(homeRedirect))
mux.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) {
n := time.Now().Format(time.RFC1123Z)
if _, err := fmt.Fprint(w, n, "\n"); err != nil {
log.Printf("error reporting time: %v", err)
} else {
log.Printf("/time reported %q", n)
}
})
}
var srv = http.Server{
Addr: bindAddress(),
Handler: mux,
}
shutdownDone := make(chan struct{})
go waitShutdownSignal(&srv, shutdownDone)
log.Printf("Starting server at %q", srv.Addr)
if err := srv.ListenAndServe(); err == http.ErrServerClosed {
<-shutdownDone
log.Printf("Bye.")
} else {
log.Fatal(err)
}
}
func waitShutdownSignal(srv *http.Server, done chan<- struct{}) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
signal := <-signals
log.Printf("Received shutdown signal %q", signal)
if err := srv.Shutdown(context.Background()); err != nil {
log.Printf("Shutdown error: %v", err)
} else {
log.Printf("Shutdown.")
}
close(done)
}
func bindAddress() string {
host := os.Getenv("HOST")
if host == "" {
host = "localhost"
}
return host + ":8080"
}
func LoggingHandler(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf(`serving '%s %s'`, r.Method, r.URL)
h.ServeHTTP(w, r)
}
}