/
delay.go
66 lines (55 loc) · 1.31 KB
/
delay.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
package api
import (
"math/rand"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
)
type RandomDelayMiddleware struct {
min int
max int
unit string
}
func NewRandomDelayMiddleware(minDelay, maxDelay int, delayUnit string) *RandomDelayMiddleware {
return &RandomDelayMiddleware{
min: minDelay,
max: maxDelay,
unit: delayUnit,
}
}
func (m *RandomDelayMiddleware) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var unit time.Duration
rand.Seed(time.Now().Unix())
switch m.unit {
case "s":
unit = time.Second
case "ms":
unit = time.Millisecond
default:
unit = time.Second
}
delay := rand.Intn(m.max-m.min) + m.min
time.Sleep(time.Duration(delay) * unit)
next.ServeHTTP(w, r)
})
}
// Delay godoc
// @Summary Delay
// @Description waits for the specified period
// @Tags HTTP API
// @Accept json
// @Produce json
// @Router /delay/{seconds} [get]
// @Success 200 {object} api.MapResponse
func (s *Server) delayHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
delay, err := strconv.Atoi(vars["wait"])
if err != nil {
s.ErrorResponse(w, r, err.Error(), http.StatusBadRequest)
return
}
time.Sleep(time.Duration(delay) * time.Second)
s.JSONResponse(w, r, map[string]int{"delay": delay})
}