golang download file and follow redirects

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

golang download file and follow redirects

问题

你想要从重定向的URL下载文件,并将文件名返回到变量filename中。你的实际代码如下:

package main

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

func downloadFile(filepath string, url string) (string, 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
  }

  // Get the real filename
  realFilename := filepath.Base(resp.Request.URL.Path)

  return realFilename, nil
}

func main() {

  var filename string = "urls.txt"
  var url1 string = "http://94.177.247.162:5000/random"

  realFilename, err := downloadFile(filename, url1)
  if err != nil {
    panic(err)
  }

  // Use the real filename
  filename = realFilename

  // Print the filename
  println(filename)
}

你可以通过在downloadFile函数中添加一些代码来获取实际的文件名。使用filepath.Base(resp.Request.URL.Path)可以从URL的路径中提取文件名。然后,你可以将实际的文件名赋值给filename变量,并打印出来。

英文:

i want to download file from redirect url, and return filename in variable filename, my actual code is :

package main

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
}

func main() {

  var filename string = "urls.txt"
  var url1 string = "http://94.177.247.162:5000/random"

  downloadFile(filename, url1)

}

how i can change my code to return real name of file downloaded in variable filename.

example output :

urlix.txt

答案1

得分: 2

重定向应该是默认跟随的。你可以使用以下代码获取访问的最终URL来获取下载链接:

finalURL := resp.Request.URL.String()

URL的最后一部分是远程文件的文件名,所以可以使用以下代码来获取文件名:

parts := strings.Split(finalURL, "/")
filename := parts[len(parts)-1]
英文:

Redirects should be followed by default. You can get the final url visited to aquire the download using

finalURL := resp.Request.URL.String()

The last part of the url is your filename on the remote so something like this should work


parts := strings.Split(finalURL, "/")
filename := parts[len(parts)-1]

huangapple
  • 本文由 发表于 2017年9月5日 19:38:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/46054094.html
匿名

发表评论

匿名网友

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

确定