-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
86 lines (67 loc) · 1.87 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
package main
import (
"context"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/kelseyhightower/envconfig"
)
type Config struct {
Host string
Port string `required:"true"`
Endpoint string `default:"/greet"`
ShutdownTimeout time.Duration `default:"5s"`
Greeting string `required:"true"`
}
func main() {
log.Println("Starting greeter service ...")
// Load the service configuration from environment variables
var c Config
if err := envconfig.Process("greeter", &c); err != nil {
log.Fatalf("Failed to process config from environment variables: %s", err)
}
// Configure the HTTP multiplexer
mux := http.NewServeMux()
mux.HandleFunc("/healthz", HealthzHandler)
mux.HandleFunc(c.Endpoint, NewGreeter(c.Greeting).Handler)
// Configure the HTTP server
httpServer := &http.Server{
Addr: net.JoinHostPort(c.Host, c.Port),
Handler: mux,
}
// Start listening from connections and serve traffic
go func() {
if err := httpServer.ListenAndServe(); err != nil {
log.Fatalf("Error shutting down server: %s", err)
}
}()
// Capture the system signals
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)
// Block until we receive it
<-signalChan
log.Println("Shutdown signal received, exiting...")
// Configure a shutdown timeout
ctx, cancel := context.WithTimeout(context.Background(), c.ShutdownTimeout)
defer cancel()
// Attempt to gracefully shutdown the server
if err := httpServer.Shutdown(ctx); err != nil {
log.Fatalf("Failed to gracefully shutdown the server: %s", err)
}
}
func HealthzHandler(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("OK"))
}
type Greeter struct {
message string
}
func NewGreeter(message string) *Greeter {
return &Greeter{message: message}
}
func (g *Greeter) Handler(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(g.message))
}