登录
首页 >  Golang >  Go问答

How to pipe an HTTP response to a file in Go?

来源:Golang技术栈

时间:2023-04-14 20:32:34 400浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《How to pipe an HTTP response to a file in Go?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到golang等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

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.

今天带大家了解了golang的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>