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

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)
}
}

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)

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{}) {