http.Handle在Golang中无法工作。

huangapple go评论83阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2014年3月1日 15:04:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/22111292.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定