@@ -3,13 +3,44 @@ package function
33import (
44 "fmt"
55 "log"
6+ "math/rand"
67 "os"
78 "time"
89)
910
11+ var r * rand.Rand
12+
13+ func init () {
14+
15+ r = rand .New (rand .NewSource (time .Now ().Unix ()))
16+ }
17+
1018// Handle a serverless request
19+ // 1. When no headers are given, sleep for the environment variable: sleep_duration.
20+ // 2. When an X-Sleep header is given, sleep for that amount of time.
21+ // 3. When the X-Min-Sleep and X-Max-Sleep headers are given, sleep for a random amount
22+ // of time between those two figures
1123func Handle (req []byte ) string {
1224
25+ if minV , ok := os .LookupEnv ("Http_X_Min_Sleep" ); ok && len (minV ) > 0 {
26+ if maxV , ok := os .LookupEnv ("Http_X_Max_Sleep" ); ok && len (maxV ) > 0 {
27+ minSleep , _ := time .ParseDuration (minV )
28+ maxSleep , _ := time .ParseDuration (maxV )
29+
30+ minMs := minSleep .Milliseconds ()
31+ maxMs := maxSleep .Milliseconds ()
32+
33+ randMs := r .Int63n (maxMs - minMs ) + minMs
34+
35+ sleepDuration , _ := time .ParseDuration (fmt .Sprintf ("%dms" , randMs ))
36+
37+ log .Printf ("Start sleep for: %fs\n " , sleepDuration .Seconds ())
38+ time .Sleep (sleepDuration )
39+ log .Printf ("Sleep done for: %fs\n " , sleepDuration .Seconds ())
40+ return fmt .Sprintf ("Slept for: %fs" , sleepDuration .Seconds ())
41+ }
42+ }
43+
1344 sleepDuration := time .Second * 2
1445
1546 if val , ok := os .LookupEnv ("Http_X_Sleep" ); ok && len (val ) > 0 {
0 commit comments