Skip to content

Commit 899d294

Browse files
committed
backend4: add option to cause errors
Signed-off-by: Benedikt Bongartz <bongartz@klimlive.de>
1 parent 18bde35 commit 899d294

1 file changed

Lines changed: 23 additions & 1 deletion

File tree

app/backend4/main.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"math/rand"
88
"net/http"
9+
"os"
910
"strconv"
1011
"time"
1112

@@ -36,6 +37,15 @@ func init() {
3637
}
3738

3839
func main() {
40+
v, ok := os.LookupEnv("ERROR_RATE")
41+
if !ok {
42+
v = "0"
43+
}
44+
rate, err := strconv.Atoi(v)
45+
if err != nil {
46+
panic(err)
47+
}
48+
3949
mux := http.NewServeMux()
4050
mux.HandleFunc("GET /rolldice", func(w http.ResponseWriter, r *http.Request) {
4151
player := "Anonymous player"
@@ -49,6 +59,10 @@ func main() {
4959
max = 6
5060
}
5161
result := doRoll(r.Context(), max)
62+
if err := causeError(r.Context(), rate); err != nil {
63+
w.WriteHeader(http.StatusInternalServerError)
64+
return
65+
}
5266
resStr := strconv.Itoa(result)
5367
rollCounter.Inc()
5468
numbersCounter.WithLabelValues(resStr).Inc()
@@ -68,10 +82,18 @@ func main() {
6882
}
6983
}
7084

85+
func causeError(_ context.Context, rate int) error {
86+
randomNumber := rand.Intn(100)
87+
if randomNumber < rate {
88+
return fmt.Errorf("internal server error")
89+
}
90+
return nil
91+
}
92+
7193
func doRoll(_ context.Context, max int) int {
7294
result := rand.Intn(max) + 1
7395
if result > 6 {
74-
time.Sleep(time.Duration(0.1*float64(result)) * time.Second)
96+
time.Sleep(time.Duration(0.5*float64(result)) * time.Second)
7597
}
7698
return result
7799
}

0 commit comments

Comments
 (0)