go loadPage问题:无效的内存地址或空指针解引用。

huangapple go评论91阅读模式
英文:

go loadPage issue: invalid memory address or nil pointer dereference

问题

我正在遵循golang.org上构建维基页面的教程(https://golang.org/doc/articles/wiki/#tmp_4),一切都进行得很顺利,直到在“使用net/http来提供维基页面”步骤中遇到了上述错误消息。我在src/github.com/user/gowiki/test.txt中有一个text.txt文件,但是loadPage(title)似乎无法访问test.txt文件。非常感谢您的帮助!谢谢!

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)
}
英文:

I'm following the golang.org tutorial on building a wiki page (https://golang.org/doc/articles/wiki/#tmp_4) and everything runs fine until I've gotten the above error message during step "Using net/http to serve wiki pages". I've got a text.txt file in src/github.com/user/gowiki/test.txt but loadPage(title) doesn't seem to be accessing the test.txt file. Any help is greatly appreciated. Thanks!

   package main

import (
	&quot;fmt&quot;
	&quot;io/ioutil&quot;
	&quot;net/http&quot;
)

type Page struct {
	Title string
	Body  []byte
}

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

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

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

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

答案1

得分: 0

你在viewHandler()函数中没有检查loadPage()返回的错误,所以如果loadPage()无法加载文件并返回nil和错误,viewHandler()会尝试使用该nil来获取页面标题和内容,这就是导致恐慌的原因。

如果loadPage()能够读取文件,那么它就能正常工作。

英文:

You are not checking the error returned by loadPage() in viewHandler() so if loadPage() can't load the file and returns nil with an error, viewHandler() tries to use that nil to obtain the page title and body and that's what causing the panic.

It works fine if loadPage() can read the file, though.

huangapple
  • 本文由 发表于 2016年12月29日 00:49:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/41366347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定