什么是web server以及golang是如何实现的

使用golang sdk中的http包实现web服务时通常会这样开始。
HandleFunc方法实现如下

1
2
3
4
5
6
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func (pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}

HandleFunc使用DefaultServeMux注册对应的处理方法(handler function。
ServeMux是一个HTTP请求的多路复用器定义为:

1
2
3
4
5
type ServeMux struct {
mu sync.RWMutex //读写锁
m map[string]muxEntry //muxEntry为匹配规则,包括explicit:是否已经存在,h:Handler,interface,处理方法接口,pattern:匹配模式
hosts bool // whether any patterns contain hostnames 是否包含域名
}