Add random delay and errors middleware

This commit is contained in:
Stefan Prodan
2018-08-21 03:12:20 +03:00
parent 0f098cf0f1
commit 593ccaa0cd
4 changed files with 39 additions and 2 deletions
+2
View File
@@ -32,6 +32,8 @@ func main() {
fs.String("ui-path", "./ui", "UI local path")
fs.String("ui-color", "blue", "UI color")
fs.String("ui-message", fmt.Sprintf("greetings from podinfo v%v", version.VERSION), "UI message")
fs.Bool("random-delay", false, "between 0 and 5 seconds random delay")
fs.Bool("random-error", false, "1/3 chances of a random response error")
fs.Int("stress-cpu", 0, "Number of CPU cores with 100 load")
fs.Int("stress-memory", 0, "MB of data to load into memory")
versionFlag := fs.Bool("version", false, "get version number")
+2 -2
View File
@@ -5,6 +5,7 @@ import (
"context"
"io/ioutil"
"net/http"
"github.com/stefanprodan/k8s-podinfo/pkg/version"
"go.uber.org/zap"
)
@@ -16,6 +17,7 @@ func (s *Server) echoHandler(w http.ResponseWriter, r *http.Request) {
s.ErrorResponse(w, r, "invalid request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
if len(s.config.BackendURL) > 0 {
backendReq, err := http.NewRequest("POST", s.config.BackendURL, bytes.NewReader(body))
@@ -75,5 +77,3 @@ func (s *Server) echoHandler(w http.ResponseWriter, r *http.Request) {
w.Write(body)
}
}
+27
View File
@@ -5,10 +5,37 @@ import (
"encoding/json"
"net/http"
"math/rand"
"time"
"github.com/stefanprodan/k8s-podinfo/pkg/version"
"go.uber.org/zap"
)
func randomDelayMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
min := 0
max := 5
rand.Seed(time.Now().Unix())
delay := rand.Intn(max-min) + min
time.Sleep(time.Duration(delay) * time.Second)
next.ServeHTTP(w, r)
})
}
func randomErrorMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rand.Seed(time.Now().Unix())
if rand.Int31n(3) == 0 {
errors := []int{http.StatusInternalServerError, http.StatusBadRequest, http.StatusConflict}
w.WriteHeader(errors[rand.Intn(len(errors))])
return
}
next.ServeHTTP(w, r)
})
}
func versionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("X-API-Version", version.VERSION)
+8
View File
@@ -34,6 +34,8 @@ type Config struct {
ConfigPath string `mapstructure:"config-path"`
Port string `mapstructure:"port"`
Hostname string `mapstructure:"hostname"`
RandomDelay bool `mapstructure:"random-delay"`
RandomError bool `mapstructure:"random-error"`
}
type Server struct {
@@ -80,6 +82,12 @@ func (s *Server) registerMiddlewares() {
httpLogger := NewLoggingMiddleware(s.logger)
s.router.Use(httpLogger.Handler)
s.router.Use(versionMiddleware)
if s.config.RandomDelay {
s.router.Use(randomDelayMiddleware)
}
if s.config.RandomError {
s.router.Use(randomErrorMiddleware)
}
}
func (s *Server) ListenAndServe(stopCh <-chan struct{}) {