| 1 |
|
| 2 |
|
| 3 |
package main |
| 4 |
|
| 5 |
import ( |
| 6 |
"context" |
| 7 |
"flag" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"log" |
| 11 |
"net/http" |
| 12 |
"os" |
| 13 |
"time" |
| 14 |
) |
| 15 |
|
| 16 |
var ( |
| 17 |
url = flag.String("url", "", "url to read from") |
| 18 |
output = flag.String("output", "", "output file to write the result too") |
| 19 |
) |
| 20 |
|
| 21 |
func download(url, output string) (err error) { |
| 22 |
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) |
| 23 |
defer cancel() |
| 24 |
|
| 25 |
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 26 |
if err != nil { |
| 27 |
return fmt.Errorf("new request failed: %w", err) |
| 28 |
} |
| 29 |
|
| 30 |
resp, err := http.DefaultClient.Do(req) |
| 31 |
if err != nil { |
| 32 |
return fmt.Errorf("request failed: %w", err) |
| 33 |
} |
| 34 |
defer resp.Body.Close() |
| 35 |
|
| 36 |
var f *os.File |
| 37 |
if output != "" { |
| 38 |
if f, err = os.Create(output); err != nil { |
| 39 |
return fmt.Errorf("create file %q failed: %w", output, err) |
| 40 |
} |
| 41 |
|
| 42 |
defer f.Close() |
| 43 |
} else { |
| 44 |
f = os.Stdout |
| 45 |
} |
| 46 |
|
| 47 |
if _, err := io.Copy(f, resp.Body); err != nil { |
| 48 |
return fmt.Errorf("body save: %w", err) |
| 49 |
} |
| 50 |
|
| 51 |
return nil |
| 52 |
} |
| 53 |
|
| 54 |
func main() { |
| 55 |
flag.Parse() |
| 56 |
|
| 57 |
switch { |
| 58 |
case len(*url) == 0: |
| 59 |
log.Fatal("missing required --url parameter") |
| 60 |
} |
| 61 |
|
| 62 |
if err := download(*url, *output); err != nil { |
| 63 |
log.Fatal(err) |
| 64 |
} |
| 65 |
} |