英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论