gopl关于《7.7 http.Handler接口》的笔记
首先查阅godoc关于以下内容的定义
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.
type HandlerFunc
type HandlerFunc func(ResponseWriter, *Request)
The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.
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.
使用示例:
func main() {
db := database{"shoes": 50, "socks": 5}
mux := http.NewServeMux()
mux.Handle("/list", http.HandlerFunc(db.list))
mux.Handle("/price", http.HandlerFunc(db.price))
log.Fatal(http.ListenAndServe("localhost:8000", mux))
}
http.HandleFunc比Handle+http.HandlerFunc使用更为简洁。
gopl中有一段来描述默认的DefaultServerMux:
net/http 包提供了一个全局的 ServeMux 实例 DefaultServerMux 和包级别的http.Handle 和 http.HandleFunc 函数。现在,为了使用 DefaultServeMux 作为服务器的主handler,我们不需要将它传给 ListenAndServe 函数;nil 值就可以工作。
func main() {
db := database{"shoes": 50, "socks": 5}
http.HandleFunc("/list", db.list)
http.HandleFunc("/price", db.price)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}