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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测