Created
December 1, 2020 01:58
-
-
Save SP3269/96a17e99aff724a672963a16ac963e13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A Web server with two endpoints - /stable (returning 200) and /unstable (going into failing state with defined probability every tick and returning 500 while in it) | |
// Based on Googles slo-burn code https://github.com/google/prometheus-slo-burn-example/tree/master/server | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"net/http" | |
"os" | |
"strconv" | |
"time" | |
"github.com/go-chi/chi" | |
"github.com/go-chi/chi/middleware" | |
) | |
func main() { | |
var failing bool // Indicator of whether the service is in failing state | |
const tick = time.Second | |
const faultProbability float32 = 0.005 // 74% chance of not failing in a minute | |
const maxFaultDuration int = 60 // In ticks | |
go func() { | |
var faultDuration int | |
for { | |
if failing { | |
faultDuration = rand.Intn(maxFaultDuration) + 1 | |
time.Sleep(time.Duration(faultDuration) * tick) | |
fmt.Print("Recovered at ", time.Now().Format(time.RFC3339), "\n") | |
failing = false | |
} else { | |
if rand.Float32() < faultProbability { | |
fmt.Print("Failed at ", time.Now().Format(time.RFC3339), "\n") | |
failing = true | |
} | |
time.Sleep(tick) | |
} | |
} | |
}() | |
r := chi.NewRouter() | |
r.Use(middleware.RequestID) | |
r.Use(middleware.Logger) | |
r.Use(middleware.Recoverer) | |
r.Get("/stable", func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("200 - serving")) | |
}) | |
r.Get("/unstable", func(w http.ResponseWriter, r *http.Request) { | |
if failing { | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("500 - in failing state")) | |
} else { | |
w.Write([]byte("200 - serving")) | |
} | |
}) | |
var port string // port # for the HTTP listener | |
portNumber, err := strconv.ParseInt(os.Getenv("PORT"), 0, 16) | |
if err == nil && portNumber > 0 && portNumber < 65536 { | |
port = fmt.Sprintf("%d", portNumber) | |
} else { | |
port = "8080" | |
} | |
fmt.Printf("Starting up on http://localhost:%s\n", port) | |
http.ListenAndServe(":"+port, r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment