github.hscsec.cn/u-root/u-root@v7.0.0+incompatible/cmds/core/wget/wget.go (about) 1 // Copyright 2012-2017 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Wget reads one file from a url and writes to stdout. 6 // 7 // Synopsis: 8 // wget URL 9 // 10 // Description: 11 // Returns a non-zero code on failure. 12 // 13 // Notes: 14 // There are a few differences with GNU wget: 15 // - Upon error, the return value is always 1. 16 // - The protocol (http/https) is mandatory. 17 // 18 // Example: 19 // wget -O google.txt http://google.com/ 20 package main 21 22 import ( 23 "context" 24 "flag" 25 "io" 26 "log" 27 "net/url" 28 "os" 29 "path" 30 31 "github.com/u-root/u-root/pkg/curl" 32 "github.com/u-root/u-root/pkg/uio" 33 ) 34 35 var ( 36 outPath = flag.String("O", "", "output file") 37 ) 38 39 func usage() { 40 log.Printf("Usage: %s [ARGS] URL\n", os.Args[0]) 41 flag.PrintDefaults() 42 os.Exit(2) 43 } 44 45 func main() { 46 log.SetPrefix("wget: ") 47 48 if flag.Parse(); flag.NArg() != 1 { 49 usage() 50 } 51 52 argURL := flag.Arg(0) 53 if argURL == "" { 54 log.Fatalln("Empty URL") 55 } 56 57 url, err := url.Parse(argURL) 58 if err != nil { 59 log.Fatalln(err) 60 } 61 62 if *outPath == "" { 63 if url.Path != "" && url.Path[len(url.Path)-1] != '/' { 64 *outPath = path.Base(url.Path) 65 } else { 66 *outPath = "index.html" 67 } 68 } 69 70 schemes := curl.Schemes{ 71 "tftp": curl.DefaultTFTPClient, 72 "http": curl.DefaultHTTPClient, 73 74 // curl.DefaultSchemes doesn't support HTTPS by default. 75 "https": curl.DefaultHTTPClient, 76 "file": &curl.LocalFileClient{}, 77 } 78 79 readerAt, err := schemes.Fetch(context.Background(), url) 80 if err != nil { 81 log.Fatalf("Failed to download %v: %v", argURL, err) 82 } 83 84 w, err := os.Create(*outPath) 85 if err != nil { 86 log.Fatalf("Failed to create output file %q: %v", *outPath, err) 87 } 88 defer w.Close() 89 90 if _, err := io.Copy(w, uio.Reader(readerAt)); err != nil { 91 log.Fatalf("Failed to read response data: %v", err) 92 } 93 }