forked from efarrer/iothrottler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
90 lines (74 loc) · 1.97 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
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright 2012 Evan Farrer. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package iothrottler_test
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"github.com/efarrer/iothrottler"
)
// Basic usage of a IOThrottlerPool to throttle reading from a file
func ExampleIOThrottlerPool() {
// Construct a bandwidth throttling pool that's limited to 100 bytes per second
pool := iothrottler.NewIOThrottlerPool(iothrottler.BytesPerSecond * 100)
defer pool.ReleasePool()
file, err := os.Open("/dev/zero")
if err != nil {
// handle error
return
}
defer file.Close()
throttledFile, err := pool.AddReader(file)
if err != nil {
// handle error
return
}
var zeros bytes.Buffer
copied, err := io.CopyN(&zeros, throttledFile, 200)
if err != nil {
// handle error
}
fmt.Printf("Copied %v bytes\n", copied)
// Output: Copied 200 bytes
}
// Throttle web requests using an IOThrottlerPool
func ExampleIOThrottlerPool_AddConn() {
// Construct a bandwidth throttling pool that's limited to 30 kilobits per
// second
pool := iothrottler.NewIOThrottlerPool(iothrottler.Kbps * 30)
defer pool.ReleasePool()
// Create our own Dial function that will be used for the http connection
throttledDial := func(nt, addr string) (c net.Conn, err error) {
conn, err := net.Dial(nt, addr)
if err != nil {
return nil, err
}
return pool.AddConn(conn)
}
// Create a transport that will use our throttled Dial function
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: throttledDial,
}
// Download the page
client := &http.Client{Transport: tr}
resp, err := client.Get("http://www.google.com")
if err != nil {
// handle error
return
}
defer resp.Body.Close()
// Read the entire contents of the body
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
return
}
fmt.Println("Downloaded www.google.com")
// Output: Downloaded www.google.com
}