https://github.com/linkdata/bwlimit
Go net.Conn bandwidth limiter
https://github.com/linkdata/bwlimit
Last synced: 7 months ago
JSON representation
Go net.Conn bandwidth limiter
- Host: GitHub
- URL: https://github.com/linkdata/bwlimit
- Owner: linkdata
- License: mit
- Created: 2024-11-15T10:01:43.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-02-05T08:23:02.000Z (about 1 year ago)
- Last Synced: 2025-02-05T09:28:25.549Z (about 1 year ago)
- Language: Go
- Size: 50.8 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://github.com/linkdata/bwlimit/actions/workflows/go.yml)
[](https://htmlpreview.github.io/?https://github.com/linkdata/bwlimit/blob/coverage/main/report.html)
[](https://goreportcard.com/report/github.com/linkdata/bwlimit)
[](https://godoc.org/github.com/linkdata/bwlimit)
# bwlimit
Go net.Conn bandwidth limiter.
Only depends on the standard library.
## Usage
`go get github.com/linkdata/bwlimit`
## Example
```go
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"time"
"github.com/linkdata/bwlimit"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello world!"))
}))
defer srv.Close()
// limit reads to 100 bytes/sec, unlimited writes
lim := bwlimit.NewLimiter(100, 0)
defer lim.Stop()
// set the default http transport DialContext
tp := http.DefaultTransport.(*http.Transport)
tp.DialContext = lim.Wrap(nil).DialContext
// make a request and time it
now := time.Now()
resp, err := http.Get(srv.URL)
elapsed := time.Since(now)
if err == nil {
var body []byte
if body, err = io.ReadAll(resp.Body); err == nil {
fmt.Printf("%v %v %q\n", elapsed >= time.Second, lim.Reads.Count.Load() > 100, string(body))
}
}
}
```