如何用go语言下载带有http请求的文件 [英] How do I download a file with a http request in go language

查看:119
本文介绍了如何用go语言下载带有http请求的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用go http软件包从go lang中的url中下载文件,并将图像保存到磁盘以供稍后显示在我的网页上。我需要这样做,因为我想从instagram下载图像并将它们保存到我的公共文件夹以便在我的网页上显示。

>

我为其他人创建了一个答案,以供其他人使用我想出的代码。

解决方案

  import(
os
net / http
io


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

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

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

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

返回零
}

它运作良好,但可能需要一点改进才能用于制作。


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.

解决方案

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.

这篇关于如何用go语言下载带有http请求的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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