英文:
http.Handle not working in Golang
问题
我尝试渲染一个模板:
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
err := fcgi.Serve(nil, http.HandlerFunc(handler))
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("404.html")
t.Execute(w, &page{Title: "not work"})
}
但是当我打开每个页面,甚至是site.com/login,我都看到404错误。我应该在哪里找到问题?
英文:
I try render a template:
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
err := fcgi.Serve(nil, http.HandlerFunc(handler))
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "text/html")
t, _ := template.ParseFiles("404.html")
t.Execute(w, &page{Title: "not work"})
}
But when I open every page, even site.com/login, I see 404.
Where can I find the problem?
答案1
得分: 2
fcgi包文档解释了:
> [...] 如果处理程序(fcgi.Serve的第二个参数)为nil,则使用http.DefaultServeMux。
为了使用在http.DefaultServeMux
中注册的http.HandleFunc
函数,您不应该将第二个参数传递给Serve
函数,否则处理程序函数将为所有请求提供服务。
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
err := fcgi.Serve(nil, nil)
}
英文:
fcgi package documentation explains
> [...] If handler [second argument of fcgi.Serve] is nil, http.DefaultServeMux is used.
In order to make use of functions registered with http.HandleFunc
in http.DefaultServeMux
you should not pass second argument to Serve
function otherwise the handler function will serve all requests.
func main() {
http.HandleFunc("/", index)
http.HandleFunc("/login", login)
err := fcgi.Serve(nil, nil)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论