2014-09-10 105 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

相關問題