ch5: fix code path

This commit is contained in:
chai2010
2016-01-21 09:58:28 +08:00
parent 3666d2f0e8
commit 20a8cf71b9
7 changed files with 19 additions and 18 deletions

View File

@@ -4,8 +4,8 @@
下面的例子獲取HTML頁面併輸出頁面的標題。title函數會檢査服務器返迴的Content-Type字段如果發現頁面不是HTML將終止函數運行返迴錯誤。
<u><i>gopl.io/ch5/title1</i></u>
```Go
gopl.io/ch5/title1
func title(url string) error {
resp, err := http.Get(url)
if err != nil {
@@ -34,7 +34,7 @@ func title(url string) error {
下面展示了運行效果:
```powershell
```
$ go build gopl.io/ch5/title1
$ ./title1 http://gopl.io
The Go Programming Language
@@ -50,8 +50,8 @@ resp.Body.close調用了多次這是爲了確保title在所有執行路徑下
defer語句經常被用於處理成對的操作如打開、關閉、連接、斷開連接、加鎖、釋放鎖。通過defer機製不論函數邏輯多複雜都能保證在任何執行路徑下資源被釋放。釋放資源的defer應該直接跟在請求資源的語句後。在下面的代碼中一條defer語句替代了之前的所有resp.Body.Close
<u><i>gopl.io/ch5/title2</i></u>
```Go
gopl.io/ch5/title2
func title(url string) error {
resp, err := http.Get(url)
if err != nil {
@@ -73,8 +73,8 @@ func title(url string) error {
在處理其他資源時也可以采用defer機製比如對文件的操作
<u><i>io/ioutil</i></u>
```Go
io/ioutil
package ioutil
func ReadFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
@@ -100,8 +100,8 @@ func lookup(key string) int {
調試複雜程序時defer機製也常被用於記録何時進入和退出函數。下例中的bigSlowOperation函數直接調用trace記録函數的被調情況。bigSlowOperation被調時trace會返迴一個函數值該函數值會在bigSlowOperation退出時被調用。通過這種方式 我們可以隻通過一條語句控製函數的入口和所有的出口甚至可以記録函數的運行時間如例子中的start。需要註意一點不要忘記defer語句後的圓括號否則本該在進入時執行的操作會在退出時執行而本該在退出時執行的永遠不會被執行。
<u><i>gopl.io/ch5/trace</i></u>
```Go
gopl.io/ch5/trace
func bigSlowOperation() {
defer trace("bigSlowOperation")() // don't forget the
extra parentheses
@@ -195,8 +195,8 @@ func doFile(filename string) error {
下面的代碼是fetch1.5節的改進版我們將http響應信息寫入本地文件而不是從標準輸出流輸出。我們通過path.Base提出url路徑的最後一段作爲文件名。
<u><i>gopl.io/ch5/fetch</i></u>
```Go
gopl.io/ch5/fetch
// Fetch downloads the URL and returns the
// name and length of the local file.
func fetch(url string) (filename string, n int64, err error) {