前言
感觉看到的另一种写法有些复杂,没必要,所以另外写了一种。可以对比一下。
https://www.cnblogs.com/taoshihan/p/8877651.html
题目: 练习5.18:不修改fetch的行为,重写fetch函数,要求使用defer机制关闭文件。
思路
defer一个函数,将close的判断放到函数里,并根据情况决定改变err参数。
代码
// 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
}
defer func() {
closeErr := f.close()
if err == nil {
err = closeErr
}
}()
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)
}
}