【声明】
非完全原创,部分内容来自于学习其他人的理论和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

本文深入解析Go语言net/http库和gin框架的源码,从注册路由、监听处理请求等方面进行详细阐述,包括结构体、方法、处理器的注册与调用,以及服务创建的整个流程。
最低0.47元/天 解锁文章
1639

被折叠的 条评论
为什么被折叠?



