Go語言聖經練習5.18

前言

感覺看到的另一種寫法有些複雜,沒必要,所以另外寫了一種。可以對比一下。
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)
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章