aboutsummaryrefslogtreecommitdiffstats
path: root/main.go
blob: 76460f3e2b5a9049cfb93ee2a394e679a0c93541 (plain) (blame)
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
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/facebookgo/httpdown"
)

var ReadyValue = http.StatusOK
var LiveValue = http.StatusOK
var hostname string

func makeNotReady(w http.ResponseWriter, r *http.Request) {
	ReadyValue = http.StatusBadRequest
	w.Header().Set("responding-pod", hostname)
	fmt.Fprintf(w, "%s", "Set Readiness Value to a failure state")

}

func makePodReady(w http.ResponseWriter, r *http.Request) {
	ReadyValue = http.StatusOK
	w.Header().Set("responding-pod", hostname)
	fmt.Fprintf(w, "%s", "Set Readiness Value to successful (OK) state")

}

func killMe(w http.ResponseWriter, r *http.Request) {
	LiveValue = http.StatusBadRequest
	w.Header().Set("responding-pod", hostname)
	fmt.Fprintf(w, "%s", "Set Liveness Value to a failure state")
}

func readinessCheck(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("responding-pod", hostname)
	http.Error(w, "", ReadyValue)
}

func livenessCheck(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("responding-pod", hostname)
	http.Error(w, "", LiveValue)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("responding-pod", hostname)
	fmt.Fprintf(w, "%s", "I'm serving traffic!")
}

func main() {
	// Force log output to stdout for Docker
	log.SetOutput(os.Stdout)

	// Delay for startup
	var delay time.Duration = (1 * time.Second)
	if os.Getenv("APPDELAY") != "" {
		var err error
		delay, err = time.ParseDuration(os.Getenv("APPDELAY"))
		if err != nil {
			log.Fatalf("Failed to parse time duration: %v", err)
		}
	}
	time.Sleep(delay)

	// Finish startup
	hostname, _ = os.Hostname()
	log.Println("Service started on port 80")

	mux := http.NewServeMux()
	mux.HandleFunc("/", rootHandler)
	mux.HandleFunc("/ping", livenessCheck)
	mux.HandleFunc("/ready", readinessCheck)
	mux.HandleFunc("/makeNotReady", makeNotReady)
	mux.HandleFunc("/makePodReady", makePodReady)
	mux.HandleFunc("/killMe", killMe)

	server := &http.Server{
		Addr:    ":80",
		Handler: mux,
	}

	hd := &httpdown.HTTP{
		StopTimeout: 10 * time.Second,
		KillTimeout: 1 * time.Second,
	}

	if err := httpdown.ListenAndServe(server, hd); err != nil {
		log.Fatalln(err)
	}

}