Go
语言中http package
包含Handle
和HandleFunc
两个函数:
func Handle
func 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 HandleFunc
func 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 main
import (
"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 main
import (
"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/*
”。
有疑问加站长微信联系(非本文作者)