...
1
16
17
18
19
20 package liveness
21
22 import (
23 "fmt"
24 "log"
25 "net/http"
26 "net/url"
27 "time"
28
29 "github.com/spf13/cobra"
30 )
31
32
33 var CmdLiveness = &cobra.Command{
34 Use: "liveness",
35 Short: "Starts a server that is alive for 10 seconds",
36 Long: "A simple server that is alive for 10 seconds, then reports unhealthy for the rest of its (hopefully) short existence",
37 Args: cobra.MaximumNArgs(0),
38 Run: main,
39 }
40
41 func main(cmd *cobra.Command, args []string) {
42 started := time.Now()
43 http.HandleFunc("/started", func(w http.ResponseWriter, r *http.Request) {
44 w.WriteHeader(200)
45 data := (time.Since(started)).String()
46 w.Write([]byte(data))
47 })
48 http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
49 duration := time.Since(started)
50 if duration.Seconds() > 10 {
51 w.WriteHeader(500)
52 w.Write([]byte(fmt.Sprintf("error: %v", duration.Seconds())))
53 } else {
54 w.WriteHeader(200)
55 w.Write([]byte("ok"))
56 }
57 })
58 http.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
59 loc, err := url.QueryUnescape(r.URL.Query().Get("loc"))
60 if err != nil {
61 http.Error(w, fmt.Sprintf("invalid redirect: %q", r.URL.Query().Get("loc")), http.StatusBadRequest)
62 return
63 }
64 http.Redirect(w, r, loc, http.StatusFound)
65 })
66 log.Fatal(http.ListenAndServe(":8080", nil))
67 }
68
View as plain text