mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-09-12 06:41:33 +00:00
good good study, day day up!
This commit is contained in:
54
vendor/gopl.io/ch5/fetch/main.go
generated
vendored
Normal file
54
vendor/gopl.io/ch5/fetch/main.go
generated
vendored
Normal file
@@ -0,0 +1,54 @@
|
||||
// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan.
|
||||
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
|
||||
// See page 148.
|
||||
|
||||
// Fetch saves the contents of a URL into a local file.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
//!+
|
||||
// Fetch downloads the URL and returns the
|
||||
// name and length of the local file.
|
||||
func fetch(url string) (filename string, n int64, err error) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
local := path.Base(resp.Request.URL.Path)
|
||||
if local == "/" {
|
||||
local = "index.html"
|
||||
}
|
||||
f, err := os.Create(local)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
n, err = io.Copy(f, resp.Body)
|
||||
// Close file, but prefer error from Copy, if any.
|
||||
if closeErr := f.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
return local, n, err
|
||||
}
|
||||
|
||||
//!-
|
||||
|
||||
func main() {
|
||||
for _, url := range os.Args[1:] {
|
||||
local, n, err := fetch(url)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "fetch %s: %v\n", url, err)
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "%s => %s (%d bytes).\n", url, local, n)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user