2014-09-10 104 views
2
package main 

import "fmt" 
import "net/http" 

func home(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "What!") 
} 

func bar(w http.ResponseWriter, r *http.Request) { 
    fmt.Fprintf(w, "Bar!") 
} 

func main() { 
    http.HandleFunc("/", home) 
    http.HandleFunc("/foo", bar) 
    http.ListenAndServe(":5678", nil) 
} 

如果我访问/foobar将运行。为什么这会在每个URL请求上得到处理?

如果我访问//any/other/path,home将运行。

任何想法为什么发生这种情况?我如何处理404的?

回答

3

这是一个设计行为 - 为/结尾的路径定义的处理程序也将处理任何子路径。

请注意,由于以斜杠结尾的模式命名为有根的子树,因此模式“/”会匹配所有未与其他已注册模式匹配的路径,而不仅仅是具有Path ==“/”的URL。

http://golang.org/pkg/net/http/#ServeMux

你要实现你自己的逻辑404从golang文档请看下面的例子:

mux := http.NewServeMux() 
mux.Handle("/api/", apiHandler{}) 
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { 
     // The "/" pattern matches everything, so we need to check 
     // that we're at the root here. 
     if req.URL.Path != "/" { 
       http.NotFound(w, req) 
       return 
     } 
     fmt.Fprintf(w, "Welcome to the home page!") 
}) 

http://golang.org/pkg/net/http/#ServeMux.Handle

2

你必须在home处理你自己的404s。

+0

我不明白。这是为什么?如果我拿走根处理程序,404的工作。看起来,当你注册一个'/'处理程序时,它充当通配符路由。 – daryl 2014-09-10 21:22:03

+0

这是一个通配符路由,如果您尝试提供文件,请使用http://golang.org/pkg/net/http/#FileServer – OneOfOne 2014-09-10 21:23:25

相关问题