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 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示