英文:
Easiest way to download a file?
问题
我可以做类似下面的事情,这会给我一个响应类,但我不确定如何将io.reader写入文件。最直接的方法是什么?
http.Get("https://www.domain.com/some.jpg")
英文:
I can do something like below, which gives me a response class, but I'm not exactly sure how to write the io.reader to a file. What is the most straightforward way?
http.Get("https://www.domain.com/some.jpg")
答案1
得分: 9
如果文件足够小,最简单的解决方案是使用ioutil.WriteFile和ioutil.ReadAll的组合:
resp, err := http.Get("your url")
bytes, err := ioutil.ReadAll(resp.Body)
err = ioutil.WriteFile(filename, bytes, 0666)
如果文件不太小,最好避免创建和填充bytes
数组。然后你应该使用io.Copy,它只是将字节从读取器复制到写入器:
resp, err := http.Get("your url")
f, err := os.Create(filename)
defer f.Close()
_, err := io.Copy(f, resp.Body)
在这两种情况下,你必须添加相关的错误处理。
英文:
If the file is small enough the easiest solution is to use ioutil.WriteFile combined with ioutil.ReadAll :
resp, err := http.Get("your url")
bytes, err := ioutil.ReadAll(resp.Body)
err = ioutil.WriteFile(filename, bytes, 0666)
If your file isn't so small, you'd better avoid creating and filling the bytes
array. Then you should use io.Copy which simply copies the bytes from the reader to the writer :
resp, err := http.Get("your url")
f, err := os.Create(filename)
defer f.Close()
_, err := io.Copy(f, resp.Body)
You must add the relevant error handling in both cases.
答案2
得分: 0
ReadFrom
在某些情况下非常有用:
package main
import (
"net/http"
"os"
)
func main() {
r, e := http.Get("http://speedtest.lax.hivelocity.net")
if e != nil {
panic(e)
}
defer r.Body.Close()
f, e := os.Create("index.html")
if e != nil {
panic(e)
}
defer f.Close()
f.ReadFrom(r.Body)
}
https://golang.org/pkg/os#File.ReadFrom
英文:
ReadFrom
is useful in some cases:
package main
import (
"net/http"
"os"
)
func main() {
r, e := http.Get("http://speedtest.lax.hivelocity.net")
if e != nil {
panic(e)
}
defer r.Body.Close()
f, e := os.Create("index.html")
if e != nil {
panic(e)
}
defer f.Close()
f.ReadFrom(r.Body)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论