Go http 原理(一)|Go主题月

570 阅读1分钟

任何实现了 ServeHttp,即为一个合法的 http.Handler

先记住这句话,然后开始梳理下面几个的关系:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

type HandlerFunc func(ResponseWriter, *Request)

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

同时需要你的 handler 函数签名为 :

func FuncName(ResponseWriter, *Request)

马上你就发现你的 handler 就和 HandlerFunc 有一致的函数签名,可以将 handler() 函数进行类型转换,转成 http.HandlerFunc

同时,http.HandlerFunc实现了http.Handler这个接口。这就串联起来了:

h = funcHandler() => h.ServeHTTP(w, r) => h(w, r)

所以上述过程中将 handler => http.Handler() 这个过程有必要的,因为我们自己写的 handler 实际上没有直接实现 ServeHTTP interface

// Handle registers the handler for the given pattern.

// ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

// HandleFunc registers the handler function for the given pattern

// Handle registers the handler for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func Handle(pattern string, handler Handler) { 
  DefaultServeMux.Handle(pattern, handler) 
}

// 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)
}