Skip to content

Commit 0fdd2fa

Browse files
committed
add example
1 parent dff89a2 commit 0fdd2fa

2 files changed

Lines changed: 85 additions & 1 deletion

File tree

README.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,48 @@
77

88
Go net.Conn bandwidth limiter.
99

10-
Only depends on the standard library.
10+
Only depends on the standard library.
11+
12+
## Usage
13+
14+
`go get github.com/linkdata/bwlimit`
15+
16+
## Example
17+
18+
```go
19+
import (
20+
"fmt"
21+
"io"
22+
"net/http"
23+
"net/http/httptest"
24+
"time"
25+
26+
"github.com/linkdata/bwlimit"
27+
)
28+
29+
func main() {
30+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31+
w.Write([]byte("Hello world!"))
32+
}))
33+
defer srv.Close()
34+
35+
// limit reads to 100 bytes/sec, unlimited writes
36+
lim := bwlimit.NewLimiter(100, 0)
37+
38+
// wrap the default http transport DialContext
39+
tp := http.DefaultTransport.(*http.Transport)
40+
tp.DialContext = lim.Wrap(tp.DialContext)
41+
42+
// make a request and time it
43+
now := time.Now()
44+
resp, err := http.Get(srv.URL)
45+
elapsed := time.Since(now)
46+
47+
if err == nil {
48+
var body []byte
49+
if body, err = io.ReadAll(resp.Body); err == nil {
50+
fmt.Printf("%v %v %q\n", elapsed >= time.Second, lim.Reads.Count.Load() > 100, string(body))
51+
}
52+
}
53+
}
54+
```

example_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package bwlimit_test
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"time"
9+
10+
"github.com/linkdata/bwlimit"
11+
)
12+
13+
func ExampleLimiter_NewLimiter() {
14+
// create a test server
15+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16+
w.Write([]byte("Hello world!"))
17+
}))
18+
defer srv.Close()
19+
20+
// limit reads to 100 bytes/sec, unlimited writes
21+
lim := bwlimit.NewLimiter(100, 0)
22+
23+
// wrap the default http transport DialContext
24+
tp := http.DefaultTransport.(*http.Transport)
25+
tp.DialContext = lim.Wrap(tp.DialContext)
26+
27+
// make a request and time it
28+
now := time.Now()
29+
resp, err := http.Get(srv.URL)
30+
elapsed := time.Since(now)
31+
32+
if err == nil {
33+
var body []byte
34+
if body, err = io.ReadAll(resp.Body); err == nil {
35+
fmt.Printf("%v %v %q\n", elapsed >= time.Second, lim.Reads.Count.Load() > 100, string(body))
36+
}
37+
}
38+
// Output:
39+
// true true "Hello world!"
40+
}

0 commit comments

Comments
 (0)