-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
62 lines (52 loc) · 1.25 KB
/
server.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
package main
import (
"context"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var port = flag.Int("port", 8080, "Port number to serve default backend 404 page.")
func main() {
flag.Parse()
index, _ := ioutil.ReadFile("index.html")
png, _ := ioutil.ReadFile("404.png")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "404.png") {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content Type", "image/png")
w.Write(png)
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, string(index))
}
})
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "ok")
})
srv := &http.Server{
Addr: fmt.Sprintf(":%d", *port),
}
go func() {
err := srv.ListenAndServe()
if err != http.ErrServerClosed {
fmt.Fprintf(os.Stderr, "could not start http server: %s\n", err)
os.Exit(1)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM)
<-stop
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
err := srv.Shutdown(ctx)
if err != nil {
fmt.Fprintf(os.Stderr, "could not graceful shutdown http server: %s\n", err)
}
}