限制http的带宽get [英] Limiting bandwidth of http get

查看:184
本文介绍了限制http的带宽get的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的初学者。

有什么方法可以限制golang的http.Get()带宽使用率吗?我发现这个: http://godoc.org/code.google.com/p/mxk/ go1 / flowcontrol ,但我不知道如何将两者拼合在一起。如何获得访问http读取器的信息?

解决方案

有一个更新版本的 github上的软件包



您使用它通过包装一个 io.Reader



这是一个完整的例子,可以很好地显示Google veeeery的主页。 / p>

这个封装了一个界面来创建新功能是非常好的Go风格,在Go的旅程中你会看到很多。

 包裹主要

进口(
io
记录
净/ 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()

//每秒限制为10字节
wrappedIn := flowrate.NewReader(resp.Body,10)

//复制到stdout
_,err = io.Copy(os.Stdout,wrappedIn)
if err! =无{
log.Fatalf(复制失败:%v,错误)
}
}


I'm a beginner to golang.

Is there any way to limit golang's http.Get() bandwidth usage? I found this: http://godoc.org/code.google.com/p/mxk/go1/flowcontrol, but I'm not sure how to piece the two together. How would I get access to the http Reader?

解决方案

There is an updated version of the package on github

You use it by wrapping an io.Reader

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

This wrapping an interface to make new functionality is very good Go style, and you'll see a lot of it in your journey into 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)
    }
}

这篇关于限制http的带宽get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆