mirror of
https://github.com/gopl-zh/gopl-zh.github.com.git
synced 2025-12-19 20:24:20 +08:00
ch5: fix code path
This commit is contained in:
@@ -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 {
|
||||
|
||||
下面的代碼是fetch(1.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) {
|
||||
|
||||
Reference in New Issue
Block a user