forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wget.go
93 lines (78 loc) · 1.83 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
90
91
92
93
// 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 (
"context"
"flag"
"io"
"log"
"net/url"
"os"
"path"
"github.com/u-root/u-root/pkg/curl"
"github.com/u-root/u-root/pkg/uio"
)
var (
outPath = flag.String("O", "", "output file")
)
func usage() {
log.Printf("Usage: %s [ARGS] URL\n", os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}
func main() {
log.SetPrefix("wget: ")
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"
}
}
schemes := curl.Schemes{
"tftp": curl.DefaultTFTPClient,
"http": curl.DefaultHTTPClient,
// curl.DefaultSchemes doesn't support HTTPS by default.
"https": curl.DefaultHTTPClient,
"file": &curl.LocalFileClient{},
}
readerAt, err := schemes.Fetch(context.Background(), url)
if err != nil {
log.Fatalf("Failed to download %v: %v", argURL, err)
}
w, err := os.Create(*outPath)
if err != nil {
log.Fatalf("Failed to create output file %q: %v", *outPath, err)
}
defer w.Close()
if _, err := io.Copy(w, uio.Reader(readerAt)); err != nil {
log.Fatalf("Failed to read response data: %v", err)
}
}