-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (66 loc) · 1.76 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
var (
host = "0.0.0.0"
port = 8080
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/user", GetUserHandler)
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", host, port),
Handler: mux,
}
// Run http server in go routine
go func() {
log.Println("Service started!")
log.Println(fmt.Sprintf("HTTP URL: http://%s:%d", host, port))
srv.ListenAndServe()
}()
timeout := time.Duration(60) * time.Second
ImplementGraceful(srv, timeout)
}
// ImplementGraceful will implement graceful shutdown to the given
// http server object. We will wait for SIGINT & SIGTERM signal
// before initiating the graceful shutdown sequence.
//
// If the existing connection no yet finished after the given timeout,
// we will forcefully shutdown the server.
func ImplementGraceful(srv *http.Server, timeout time.Duration) {
// Make channel, and listen for SIGINT & SIGTERM
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
// Block until receive the signal
oscall := <-c
log.Println(fmt.Sprintf("Signal received:%+v", oscall))
// Create a deadline to wait for
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
// Gracefully shutdown the http server
srv.Shutdown(ctx)
// Exiting the program
log.Println("Shutting down service!")
os.Exit(0)
}
// GetUserHandler implementation
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
user := map[string]interface{}{
"id": 1,
"name": "John Doe",
}
ub, _ := json.Marshal(user)
// Add 5 second timeout to simulate slow upstream services
time.Sleep(5 * time.Second)
w.Header().Set("Content-Type", "application/json")
w.Write(ub)
}