我仍在学习如何使用Go进行网页开发,但当我试图创建一个简单的网站时,我面临着以下困难:
package main
import (
"fmt"
"html/template"
"net/http"
)
func main() {
fs := http.FileServer(http.Dir(""))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("index.html")
tmpl.Execute(w, nil)
})
/**
* This route will return a 404 error
*/
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Test page")
})
/**
* If I replace fs to nil, /test route will be work, but non-existent routes
* will be return index.html template (home router) instead 404 error. Why?
*/
http.ListenAndServe(":80", fs)
}
http.FileServer
和http.HandleFunc
之间存在冲突.
例如,当我写下:http.ListenAndServe(":80", nil)
时,所有的路由(http.HandleFunc
)都会起作用,但如果我try 这样做:
http.ListenAndServe(":80", http. FileServer(http.Dir("")))
个
无路由可用(http.HandleFunc("/"))
除外.为什么?
以及如何覆盖404错误页面?我希望Go有一个类似http.HandleError
的方法,可以接受http.ResponseWriter
和http.Request
的接口,但我找不到任何类似的东西.