/
example_test.go
39 lines (36 loc) · 1.23 KB
/
example_test.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
package ratelimit_test
import (
"fmt"
"github.com/dougnukem/ratelimit"
"time"
)
func ExampleRateLimiter_Wait() {
// 2 requests per second refreshing 2 capacity every second
r := ratelimit.NewRateLimiter(time.Second, 2, 2)
start := time.Now()
r.Wait()
fmt.Printf("r.Wait() elapsed less than 500 ms [%t]\n", time.Now().Sub(start) < 500*time.Millisecond)
r.Wait()
fmt.Printf("r.Wait() elapsed less than 500 ms [%t]\n", time.Now().Sub(start) < 500*time.Millisecond)
r.Wait()
fmt.Printf("r.Wait() elapsed greater than 500 ms [%t]\n", time.Now().Sub(start) > 500*time.Millisecond)
// Output:
// r.Wait() elapsed less than 500 ms [true]
// r.Wait() elapsed less than 500 ms [true]
// r.Wait() elapsed greater than 500 ms [true]
}
func ExampleRateLimiter_WaitMaxDuration() {
// 2 requests per second refreshing 2 capacity every second
r := ratelimit.NewRateLimiter(time.Second, 2, 2)
maxDuration := 500 * time.Millisecond
s := r.WaitMaxDuration(maxDuration)
fmt.Printf("r.Wait() success[%t]\n", s)
s = r.WaitMaxDuration(maxDuration)
fmt.Printf("r.Wait() success[%t]\n", s)
s = r.WaitMaxDuration(maxDuration)
fmt.Printf("r.Wait() success[%t]\n", s)
// Output:
// r.Wait() success[true]
// r.Wait() success[true]
// r.Wait() success[false]
}