dongzhi7641 2016-12-28 16:49
浏览 55
已采纳

进入loadPage问题:无效的内存地址或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 (
    "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)
}
  • 写回答

1条回答 默认 最新

  • dqrdlqpo775594 2016-12-28 16:57
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?