/
example.go
54 lines (43 loc) · 1.11 KB
/
example.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
package main
import (
"context"
"flag"
"fmt"
"html"
"log"
"net/http"
"time"
"github.com/MatthewLavine/gracefulshutdown"
)
var (
port = flag.String("port", ":8080", "Server port")
)
func main() {
ctx := context.Background()
httpServer := &http.Server{
Addr: *port,
}
// Gracefully shut down the HTTP server.
gracefulshutdown.AddShutdownHandler(func() error {
log.Println("Shutting down HTTP server...")
defer log.Println("HTTP server shut down.")
return httpServer.Shutdown(ctx)
})
// Perform application specific cleanup before exiting.
gracefulshutdown.AddShutdownHandler(func() error {
log.Println("Running some cleanup routine...")
time.Sleep(5 * time.Second)
log.Println("Cleanup routine complete.")
return nil
})
log.Printf("Server listening on port %s", *port)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
if err := httpServer.ListenAndServe(); err != nil {
if err != http.ErrServerClosed {
log.Fatalf("Could not listen on %s: %v\n", *port, err)
}
}
gracefulshutdown.WaitForShutdown()
}