github.com/rck/u-root@v0.0.0-20180106144920-7eb602e381bb/cmds/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 http://google.com/ > e100.html
    20  package main
    21  
    22  import (
    23  	"flag"
    24  	"fmt"
    25  	"io"
    26  	"log"
    27  	"net/http"
    28  	"net/url"
    29  	"os"
    30  	"path"
    31  )
    32  
    33  var (
    34  	outPath = flag.String("O", "", "output file")
    35  )
    36  
    37  func wget(arg, fileName string) error {
    38  	resp, err := http.Get(arg)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	defer resp.Body.Close()
    43  	if resp.StatusCode != 200 {
    44  		return fmt.Errorf("non-200 HTTP status: %d", resp.StatusCode)
    45  	}
    46  
    47  	w, err := os.Create(fileName)
    48  	if err != nil {
    49  		return err
    50  	}
    51  	defer w.Close()
    52  
    53  	_, err = io.Copy(w, resp.Body)
    54  	return err
    55  }
    56  
    57  func usage() {
    58  	log.Printf("Usage: %s [ARGS] URL\n", os.Args[0])
    59  	flag.PrintDefaults()
    60  	os.Exit(2)
    61  }
    62  
    63  func main() {
    64  	if flag.Parse(); flag.NArg() != 1 {
    65  		usage()
    66  	}
    67  
    68  	argURL := flag.Arg(0)
    69  	if argURL == "" {
    70  		log.Fatalln("Empty URL")
    71  	}
    72  
    73  	url, err := url.Parse(argURL)
    74  	if err != nil {
    75  		log.Fatalln(err)
    76  	}
    77  
    78  	if *outPath == "" {
    79  		if url.Path != "" && url.Path[len(url.Path)-1] != '/' {
    80  			*outPath = path.Base(url.Path)
    81  		} else {
    82  			*outPath = "index.html"
    83  		}
    84  	}
    85  
    86  	if err := wget(argURL, *outPath); err != nil {
    87  		log.Fatalln(err)
    88  	}
    89  }