HTTP get throughput limit

I'm starting a golang.

Is there a way to limit the use of golang http.Get () bandwidth? I found this: http://godoc.org/code.google.com/p/mxk/go1/flowcontrol , but I'm not sure how to put them together. How to access http reader?

+5
source share
2 answers

There is an updated version of the package on github

You use it by wrapping io.Reader

Here is a complete example that will show the Google homepage veeeery sloooowly.

This new feature wrapping interface is a very good Go style and you will see a lot in your journey to Go.

 package main import ( "io" "log" "net/http" "os" "github.com/mxk/go-flowrate/flowrate" ) func main() { resp, err := http.Get("http://google.com") if err != nil { log.Fatalf("Get failed: %v", err) } defer resp.Body.Close() // Limit to 10 bytes per second wrappedIn := flowrate.NewReader(resp.Body, 10) // Copy to stdout _, err = io.Copy(os.Stdout, wrappedIn) if err != nil { log.Fatalf("Copy failed: %v", err) } } 
+2
source

Thirdparty packages have convenient wrappers. But if you're curious how everything works under the hood, it's pretty easy.

 package main import ( "io" "net/http" "os" "time" ) var datachunk int64 = 500 //Bytes var timelapse time.Duration = 1 //per seconds func main() { responce, _ := http.Get("http://google.com") for range time.Tick(timelapse * time.Second) { _, err :=io.CopyN(os.Stdout, responce.Body, datachunk) if err!=nil {break} } } 

Nothing magical.

+11
source

Source: https://habr.com/ru/post/1210768/


All Articles