如何在Go中管理HTTP响应文件? [英] How to pipe an HTTP response to a file in Go?

查看:124
本文介绍了如何在Go中管理HTTP响应文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将下面的代码转换为使用流/管道,以便我不需要将全部内容读入内存?
类似于:
http.Get(http://example.com/).Pipe(./data.txt)

 包主
导入(net / http;io / ioutil)

func main(){
resp,err:= http.Get(http://example.com/)
check(err)
defer resp.Body.Close( )
body,err:= ioutil.ReadAll(resp.Body)
check(err)
err = ioutil.WriteFile(./ data.txt,body,0666)
$ check(err)
}
func check(e error){
if e!= nil {
panic(e)
}
}


解决方案

> io.Copy ()?其文档可在以下网址找到: http://golang.org/pkg/io/#Copy



尽管这很简单。给它一个 io.Reader 和一个 io.Writer ,它将数据复制一次,一次一个小块(例如,不是所有的内存在一次)。

所以你可以尝试写如下:

  func main(){
resp,err:= http.Get(...)
check(err)
defer resp.Body.Close( )
out,err:= os.Create(filename.ext)
if err!= nil {
// panic?

推迟出.Close()
io.Copy(out,resp.Body)
}

我没有测试过以上;我刚刚从上面的例子中快速入侵了它,但它应该接近,如果不是钱的话。


How do I convert the below code to use streams/pipes so that I don't need to read the full content into memory? Something like: http.Get("http://example.com/").Pipe("./data.txt")

package main
import ("net/http";"io/ioutil")

func main() {
        resp, err := http.Get("http://example.com/")
        check(err)
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        check(err)
        err = ioutil.WriteFile("./data.txt", body, 0666)
        check(err)
}
func check(e error) {
        if e != nil {
                panic(e)
        }
}

解决方案

How about io.Copy()? Its documentation can be found at: http://golang.org/pkg/io/#Copy

It's pretty simple, though. Give it an io.Reader and an io.Writer and it copies the data over, one small chunk at a time (e.g. not all in memory at once).

So you might try writing something like:

func main() {
  resp, err := http.Get("...")
  check(err)
  defer resp.Body.Close()
  out, err := os.Create("filename.ext")
  if err != nil {
    // panic?
  }
  defer out.Close()
  io.Copy(out, resp.Body)
}

I haven't tested the above; I just hacked it together quickly from your above example, but it should be close if not on the money.

这篇关于如何在Go中管理HTTP响应文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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