Reputation: 1141
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
Upvotes: 0
Views: 2017
Reputation: 6069
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]
Upvotes: 2