How do I download a file with a http request in go language

huangapple go评论79阅读模式
英文:

How do I download a file with a http request in go language

问题

我想使用Go语言的http包从URL下载文件,并将图像保存到磁盘上,以便稍后在我的网页上显示。我该如何做到这一点?

我需要这样做是因为我想从Instagram下载图片,并将它们保存到我的公共文件夹中,以便在我的网页上显示。

我在下面创建了一个答案,供其他人使用我编写的代码。

英文:

I want to download a file from an url in go lang using the go http package and save the image to disk for later display on my webpage. How do I do this?

I need to do this because I want to download images from instagram and save them to my public folder for display on my webpage.

I created an answer below for others to use the code I came up with.

答案1

得分: 15

经过一些研究,我得到了以下代码:

import (
    "os"
    "net/http"
    "io"
)

func downloadFile(filepath string, url string) (err error) {

  // 创建文件
  out, err := os.Create(filepath)
  if err != nil  {
    return err
  }
  defer out.Close()

  // 获取数据
  resp, err := http.Get(url)
  if err != nil {
    return err
  }
  defer resp.Body.Close()

  // 将数据写入文件
  _, err = io.Copy(out, resp.Body)
  if err != nil  {
    return err
  }

  return nil
}

这段代码运行良好,但在生产环境中可能需要进行一些改进。

英文:

After some research I came up with this.

import (
    "os"
    "net/http"
    "io"
)

func downloadFile(filepath string, url string) (err error) {

  // Create the file
  out, err := os.Create(filepath)
  if err != nil  {
    return err
  }
  defer out.Close()

  // Get the data
  resp, err := http.Get(url)
  if err != nil {
    return err
  }
  defer resp.Body.Close()

  // Writer the body to file
  _, err = io.Copy(out, resp.Body)
  if err != nil  {
    return err
  }

  return nil
}

It works well but might need a bit of refinement for use in production.

huangapple
  • 本文由 发表于 2015年11月22日 00:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/33845770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定