@@ -3,13 +3,44 @@ package function
3
3
import (
4
4
"fmt"
5
5
"log"
6
+ "math/rand"
6
7
"os"
7
8
"time"
8
9
)
9
10
11
+ var r * rand.Rand
12
+
13
+ func init () {
14
+
15
+ r = rand .New (rand .NewSource (time .Now ().Unix ()))
16
+ }
17
+
10
18
// 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
11
23
func Handle (req []byte ) string {
12
24
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
+
13
44
sleepDuration := time .Second * 2
14
45
15
46
if val , ok := os .LookupEnv ("Http_X_Sleep" ); ok && len (val ) > 0 {
0 commit comments