【声明】
非完全原创,部分内容来自于学习其他人的理论和B站视频。如果有侵权,请联系我,可以立即删除掉。
一、net/http
源码解读
1、从官方的demo开始
//给路由地址添加匿名函数,即DefaultServeMux的处理器函数
http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080", nil))
1.1、HandleFunc
:注册路由
HandleFunc
将用户指定的路由地址pattern
和对应的处理器handler
作为一个map
实体注册到默认的ServeMux
结构体对象DefaultServeMux
的m[pattern]
中
// 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)
}
1.1.1、ServeMux
结构体对象DefaultServeMux
// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
type ServeMux struct {
mu sync.RWMutex //一个读写锁,确保每次客户端请求的处理不受其他请求干扰
m map[string]muxEntry //添加处理器handler和路由地址pattern到m[pattern]中
es []muxEntry // slice of entries sorted from longest to shortest.
hosts bool // whether any patterns contain hostnames
}
type muxEntry struct {
h Handler
pattern string
}
ServeMux
是一个HTTP请求复用器。它根据注册模式列表es
匹配每个传入请求的URL,并调用与URL最匹配的模式(按照最长匹配规则)的处理程序。其内部map
类型的m
存储了处理器handler
和路由地址pattern
1.1.2、ServeMux
结构体的HandleFunc
方法
HandleFunc
方法将传入的处理器handler
和路由地址pattern
包装为一个muxEntry
存入到m[pattern]
中,如果传入的路由地址是某种前缀的路由子树的路由子树,则将路由子树 按照前缀字符串由大到小的长度的顺序 添加到模式列表es
中
// 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 registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler)