這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Go語言中http package包含Handle和HandleFunc兩個函數:
func Handlefunc Handle(pattern string, handler Handler)Handle registers the handler for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.func HandleFuncfunc HandleFunc(pattern string, handler func(ResponseWriter, *Request))HandleFunc registers the handler function for the given pattern in the DefaultServeMux. The documentation for ServeMux explains how patterns are matched.
Handle函數的handler參數是個interface:
type Handler interface { ServeHTTP(ResponseWriter, *Request)}
而HandleFunc的handler參數就是一個原型為func(ResponseWriter, *Request)的函數。
參考下例(使用Handle):
package mainimport ( "net/http" "log")type httpServer struct {}func (server httpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Write([]byte(r.URL.Path))}func main() { var server httpServer http.Handle("/", server) log.Fatal(http.ListenAndServe("localhost:9000", nil))}
使用HandleFunc:
package mainimport ( "net/http" "log")func main() { http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request){ w.Write([]byte(r.URL.Path)) }) log.Fatal(http.ListenAndServe("localhost:9000", nil))}
根據The Go Programming Language:
A handler pattern that ends with a slash matches any URL that has the pattern as a prefix. Behind the scenes, the server runs the handler for each incoming request in a separate goroutine so that it can serve multiple requests simultaneously.
因此,如果http.Handle和http.HandleFunc所指定的handle pattern是“/”,則匹配所有的pattern;而“/foo/”則會匹配所有“/foo/*”。