forked from u-root/u-root
/
wget.go
89 lines (77 loc) · 1.54 KB
/
wget.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2012-2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Wget reads one file from a url and writes to stdout.
//
// Synopsis:
// wget URL
//
// Description:
// Returns a non-zero code on failure.
//
// Notes:
// There are a few differences with GNU wget:
// - Upon error, the return value is always 1.
// - The protocol (http/https) is mandatory.
//
// Example:
// wget -O google.txt http://google.com/
package main
import (
"flag"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
)
var (
outPath = flag.String("O", "", "output file")
)
func wget(arg, fileName string) error {
resp, err := http.Get(arg)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("non-200 HTTP status: %d", resp.StatusCode)
}
w, err := os.Create(fileName)
if err != nil {
return err
}
defer w.Close()
_, err = io.Copy(w, resp.Body)
return err
}
func usage() {
log.Printf("Usage: %s [ARGS] URL\n", os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}
func main() {
if flag.Parse(); flag.NArg() != 1 {
usage()
}
argURL := flag.Arg(0)
if argURL == "" {
log.Fatalln("Empty URL")
}
url, err := url.Parse(argURL)
if err != nil {
log.Fatalln(err)
}
if *outPath == "" {
if url.Path != "" && url.Path[len(url.Path)-1] != '/' {
*outPath = path.Base(url.Path)
} else {
*outPath = "index.html"
}
}
if err := wget(argURL, *outPath); err != nil {
log.Fatalln(err)
}
}