forked from hashicorp/http-echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (78 loc) · 2.1 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
94
95
96
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/hashicorp/http-echo/version"
)
var (
listenFlag = flag.String("listen", ":5678", "address and port to listen")
textFlag = flag.String("text", "", "text to put on the webpage")
versionFlag = flag.Bool("version", false, "display version information")
headersFlag = flag.Bool("headers", false, "return received headers")
// stdoutW and stderrW are for overriding in test.
stdoutW = os.Stdout
stderrW = os.Stderr
)
func main() {
flag.Parse()
// Asking for the version?
if *versionFlag {
fmt.Fprintln(stderrW, version.HumanVersion)
os.Exit(0)
}
// Validation
if *textFlag == "" {
fmt.Fprintln(stderrW, "Missing -text option!")
os.Exit(127)
}
args := flag.Args()
if len(args) > 0 {
fmt.Fprintln(stderrW, "Too many arguments!")
os.Exit(127)
}
// Flag gets printed as a page
mux := http.NewServeMux()
mux.HandleFunc("/", httpLog(stdoutW, withAppHeaders(httpEcho(*textFlag), *headersFlag)))
// Health endpoint
mux.HandleFunc("/health", withAppHeaders(httpHealth(), false))
server := &http.Server{
Addr: *listenFlag,
Handler: mux,
}
serverCh := make(chan struct{})
go func() {
log.Printf("[INFO] server is listening on %s\n", *listenFlag)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("[ERR] server exited with: %s", err)
}
close(serverCh)
}()
signalCh := make(chan os.Signal, 1)
signal.Notify(signalCh, os.Interrupt)
// Wait for interrupt
<-signalCh
log.Printf("[INFO] received interrupt, shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("[ERR] failed to shutdown server: %s", err)
}
// If we got this far, it was an interrupt, so don't exit cleanly
os.Exit(2)
}
func httpEcho(v string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, v)
}
}
func httpHealth() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, `{"status":"ok"}`)
}
}