Created
August 16, 2016 09:20
-
-
Save derlin/2ddaf9c47c62bf620f5d9c0cf1b799ff to your computer and use it in GitHub Desktop.
Download resources from a url with go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
"strings" | |
) | |
func downloadFromUrl(url string) { | |
tokens := strings.Split(url, "/") | |
fileName := tokens[len(tokens)-1] | |
fmt.Println("Downloading", url, "to", fileName) | |
// TODO: check file existence first with io.IsExist | |
output, err := os.Create(fileName) | |
if err != nil { | |
fmt.Println("Error while creating", fileName, "-", err) | |
return | |
} | |
defer output.Close() | |
response, err := http.Get(url) | |
if err != nil { | |
fmt.Println("Error while downloading", url, "-", err) | |
return | |
} | |
defer response.Body.Close() | |
n, err := io.Copy(output, response.Body) | |
if err != nil { | |
fmt.Println("Error while downloading", url, "-", err) | |
return | |
} | |
fmt.Println(n, "bytes downloaded.") | |
} | |
func main() { | |
argc := len(os.Args) | |
if argc < 2 { | |
fmt.Printf("usage: %s url [urls]\n", os.Args[0]) | |
os.Exit(1) | |
} | |
for i := 1; i < argc; i++ { | |
downloadFromUrl(os.Args[i]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment