关于http包中的handler

3.4节中提到了:Handler在http包中是一个接口,其中包含ServeHTTP方法,然而我们在使用http包时,并不用显式地实现ServeHTTP方法,http包会自动帮我们实现ServeHTTP方法,从而实现Handler接口。
3.4节在这里讲的有一些简略,我重新梳理下自己梳理对这块实现的理解,顺带结合go15.6中http包的源码捋一捋路由规则注册的全过程:
我们在使用默认路由时,首先要做的就是向路由中注册路由规则:

http.HandleFunc("/", sayhelloName)

之后http包中的默认路由就会为我们添加这条路由规则:

  1. 首先,2473~2483行,http.HandleFunc会调用DefaultServeMux.HandleFunc:
    // HandleFunc registers the handler function for the given pattern
    // in the DefaultServeMux.
    // The documentation for ServeMux explains how patterns are matched.
    func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
     DefaultServeMux.HandleFunc(pattern, handler)
    }
  2. 在2465-2471行,DefaultServeMux.HandleFunc会调用DefauleServeMux.Handle:
    // HandleFunc registers the handler function for the given pattern.
    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
     if handler == nil {
         panic("http: nil handler")
     }
     mux.Handle(pattern, HandlerFunc(handler))
    }
    注意调用Handle时的第二个参数HandlerFunc(handler),这里将handler做了类型强转,把函数handler转成了HandlerFunc类型的函数,我们看一下type Handler的声明:
    // 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.
    type HandlerFunc func(ResponseWriter, *Request)
    // ServeHTTP calls f(w, r).
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
     f(w, r)
    }
    在2034-2043行,定义了HandlerFunc类型与HandlerFunc.ServeHTTP方法,注意HandlerFunc.ServeHTTP的实现:“f(w, r)”,此处表明调用HandlerFunc(w, r)其实就是调用HandlerFunc.ServeHTTP(w, r)。
    至此,我们自定义的handler就实现了ServeHTTP方法,进而实现了Handler接口。
  3. DefaultServeMux.Handle函数向DefaultServeMux 的 map [string] muxEntry中添加对应的handler和路由规则,就如3.4节中提到的一样。
go
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
1
粉丝
0
喜欢
0
收藏
0
排名:3421
访问:59
私信
所有博文
博客标签
社区赞助商