Golang中修复编写Web应用程序时遇到的问题

Golang中修复编写Web应用程序时遇到的问题 发现 编写Web应用程序 - Go编程语言 中存在一个小错误。

当此Web服务器运行时,访问 http://localhost:8080/view/test 应显示一个标题为“test”的页面,其中包含“Hello world”字样。

应改为

当此Web服务器运行时,访问 http://localhost:8080/view/TestPage 应显示一个标题为“test”的页面,其中包含“Hello world”字样。

否则你会遇到这个错误

2024/05/26 15:01:32 http: panic serving [::1]:52401: runtime error: invalid memory address or nil pointer dereference
goroutine 42 [running]:
net/http.(*conn).serve.func1()
        /usr/local/go/src/net/http/server.go:1898 +0xbe
panic({0x612ee40?, 0x62f4a50?})
        /usr/local/go/src/runtime/panic.go:770 +0x132
main.viewHandler({0x6173ff0, 0xc0001be620}, 0xc0001aab30?)
        /Users/pcam/DEV/GO/GOWIKI/wiki.go:32 +0x96
net/http.HandlerFunc.ServeHTTP(0x6300130?, {0x6173ff0?, 0xc0001be620?}, 0x607961a?)
        /usr/local/go/src/net/http/server.go:2166 +0x29
net/http.(*ServeMux).ServeHTTP(0x5ed40d9?, {0x6173ff0, 0xc0001be620}, 0xc0001ba480)
        /usr/local/go/src/net/http/server.go:2683 +0x1ad
net/http.serverHandler.ServeHTTP({0xc0001946c0?}, {0x6173ff0?, 0xc0001be620?}, 0x6?)
        /usr/local/go/src/net/http/server.go:3137 +0x8e
net/http.(*conn).serve(0xc0001986c0, {0x6174458, 0xc00007ccf0})
        /usr/local/go/src/net/http/server.go:2039 +0x5e8
created by net/http.(*Server).Serve in goroutine 1
        /usr/local/go/src/net/http/server.go:3285 +0x4b4

更多关于Golang中修复编写Web应用程序时遇到的问题的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

文章中实际上写道:

让我们创建一些页面数据(作为 test.txt),编译我们的代码,并尝试提供一个维基页面。 在你的编辑器中打开 test.txt 文件,并在其中保存字符串“Hello world”(不带引号)。

更多关于Golang中修复编写Web应用程序时遇到的问题的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


确实,Go官方Wiki教程中的这个细节很重要。问题出现在viewHandler函数中,当访问/view/test时,程序会尝试加载名为test.txt的文件,但初始数据文件是TestPage.txt

以下是修复后的关键代码部分:

func viewHandler(w http.ResponseWriter, r *http.Request) {
    title := r.URL.Path[len("/view/"):]
    p, err := loadPage(title)
    if err != nil {
        // 重定向到编辑页面,而不是直接panic
        http.Redirect(w, r, "/edit/"+title, http.StatusFound)
        return
    }
    renderTemplate(w, "view", p)
}

// 或者在初始化时创建正确的文件
func init() {
    // 确保初始页面文件存在
    p1 := &Page{Title: "TestPage", Body: []byte("Hello world")}
    p1.save()
}

更完整的解决方案是在main()函数中初始化默认页面:

func main() {
    // 创建初始页面
    initPage := &Page{Title: "TestPage", Body: []byte("Hello world")}
    initPage.save()
    
    http.HandleFunc("/view/", viewHandler)
    http.HandleFunc("/edit/", editHandler)
    http.HandleFunc("/save/", saveHandler)
    
    log.Fatal(http.ListenAndServe(":8080", nil))
}

这样访问http://localhost:8080/view/TestPage就能正确显示内容,而访问/view/test则会重定向到编辑页面让用户创建新内容。

回到顶部