如何在Go中通过管道将HTTP响应传递给文件?

如何在Go中通过管道将HTTP响应传递给文件?

问题描述:

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)
        }
}

如何转换以下代码以使用流/管道,这样我就不需要阅读全部内容 类似于: http.Get(“ http://example.com/”).Pipe(“ ./data.txt”) code> p>

 包main 
import(“ net / http”;“ io / ioutil”)
 
func main(){
 resp,err:= http.Get(“ http://example.com  /“)
 check(err)
延迟res.Body.Close()
主体,err:= ioutil.ReadAll(resp.Body)
 check(err)
 err = ioutil.WriteFile(”。  /data.txt“,正文,0666)
 check(err)
} 
func check(e error){
 if e!= nil {
 panic(e)
} 
} 
   pre> 
  div>

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.