net/http 源码分析
socket交互过程:
)
golang建立http服务器的差不多两步:
-
注册路由,提供url和handle函数的映射
//示例 http.HandleFunc("/", indexHeander) http.HandleFunc("/index", indexHandle)
-
实例化server,监听端口,建立连接
log.Fatal(http.ListenAndServe(":8999", nil))
先讲讲用来注册路由的HandleFunc函数.
HandleFunc函数结构简单:使用默认的多路复用器注册路由
可以看到,DefaultServeMux就是一个ServeMux的实例
//DefaultServeMux声明如下
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
type ServeMux struct {
mu sync.RWMutex//读写锁
m map[string]muxEntry
es []muxEntry // slice of entries sorted from longest to shortest.
hosts bool // whether any patterns contain hostnames
}
...
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.