-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmain.go
116 lines (100 loc) · 2.32 KB
/
main.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"context"
"crypto/sha256"
"fmt"
"math/rand"
"net/http"
"os"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
rollCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "dice_roll_count",
Help: "How often the dice was rolled",
},
)
numbersCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "dice_numbers_count",
Help: "How often each number of the dice was rolled",
},
[]string{"number"},
)
)
func init() {
prometheus.MustRegister(rollCounter)
prometheus.MustRegister(numbersCounter)
}
func main() {
v, ok := os.LookupEnv("RATE_ERROR")
if !ok {
v = "0"
}
rateError, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
v, ok = os.LookupEnv("RATE_HIGH_DELAY")
if !ok {
v = "0"
}
rateDelay, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
mux := http.NewServeMux()
mux.HandleFunc("GET /rolldice", func(w http.ResponseWriter, r *http.Request) {
player := "Anonymous player"
if p := r.URL.Query().Get("player"); p != "" {
player = p
}
max := 8
if fmt.Sprintf("%x", sha256.Sum256([]byte(player))) == "f4b7c19317c929d2a34297d6229defe5262fa556ef654b600fc98f02c6d87fdc" {
max = 8
} else {
max = 6
}
result := doRoll(r.Context(), max)
causeDelay(r.Context(), rateDelay)
if err := causeError(r.Context(), rateError); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
resStr := strconv.Itoa(result)
rollCounter.Inc()
numbersCounter.WithLabelValues(resStr).Inc()
if _, err := w.Write([]byte(resStr)); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
})
mux.HandleFunc("GET /metrics", promhttp.Handler().ServeHTTP)
srv := &http.Server{
Addr: "0.0.0.0:5165",
Handler: mux,
}
if err := srv.ListenAndServe(); err != nil {
panic(err)
}
}
func causeError(ctx context.Context, rate int) error {
randomNumber := rand.Intn(100)
if randomNumber < rate {
err := fmt.Errorf("number(%d)) < rate(%d)", randomNumber, rate)
return err
}
return nil
}
func causeDelay(ctx context.Context, rate int) {
randomNumber := rand.Intn(100)
if randomNumber < rate {
time.Sleep(time.Duration(2+rand.Intn(3)) * time.Second)
}
}
func doRoll(_ context.Context, max int) int {
return rand.Intn(max) + 1
}