2016-12-28 78 views
0

我正在關注構建wiki頁面的golang.org教程(https://golang.org/doc/articles/wiki/#tmp_4),並且一切正常,直到我在步驟「使用net/http服務維基頁面「。我在src/github.com/user/gowiki/test.txt中有一個text.txt文件,但loadPage(標題)似乎沒有訪問test.txt文件。任何幫助是極大的讚賞。謝謝!go loadPage問題:無效的內存地址或無指針解除引用

package main 

import (
    "fmt" 
    "io/ioutil" 
    "net/http" 
) 

type Page struct { 
    Title string 
    Body []byte 
} 

func (p *Page) save() error { 
    filename := p.Title + ".txt" 
    return ioutil.WriteFile(filename, p.Body, 0600) 
} 

func loadPage(title string) (*Page, error) { 
    filename := title + ".txt" 
    body, err := ioutil.ReadFile(filename) 
    if err != nil { 
     return nil, err 
    } 
    return &Page{Title: title, Body: body}, nil 
} 

func viewHandler(w http.ResponseWriter, r *http.Request) { 
    title := r.URL.Path[len("/view/"):] 
    p, _ := loadPage(title) 
    fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body) 
} 

func main() { 
    http.HandleFunc("/view/", viewHandler) 
    http.ListenAndServe(":8080", nil) 
} 

回答

0

您還沒有核對loadPage()中的ViewHandler(返回的錯誤),所以如果loadPage()不能加載該文件,並返回一個錯誤爲零,ViewHandler的()試圖使用零獲得頁面標題和正文,這就是導致恐慌的原因。

它工作正常,但如果loadPage()可以讀取文件。

+0

ahhh得到了它,我創建了一個if語句返回,如果有錯誤,並打印錯誤,現在看到「打開test.txt:沒有這樣的文件或目錄」確認loadPage()找不到文件。我玩過保存文件的位置以及從哪裏啓動服務器,現在它已加載。謝謝! – jj1111

+0

@ jj1111不客氣。如果您滿意,您應該接受我的答案。 –

相關問題