初探 Go http 服务器源码

663 阅读1分钟

这是我参与更文挑战的第2天,活动详情查看: 更文挑战

如果❤️我的文章有帮助,欢迎点赞、关注。这是对我继续技术创作最大的鼓励。更多往期文章在我的个人博客

初探 Go http 服务器源码

注册路由

注册路由 源码在 golang\src\net\http\server.go 文件

code-snapshot.png

ServeMux是一个HTTP请求多路复用的服务器,它将每个请求 URL已注册路由列表进行匹配,并调用 匹配路由对应的处理程序

这里需要说明的是 handler func(ResponseWriter, *Request) 是把一个函数 作为 参数 传递给 HandleFunc 方法,实现函数的回调(闭包)

实现 http 服务端代码

func main() {
	// 创建路由器
	mux := http.NewServeMux()
	// 设置路由规则
	mux.HandleFunc("/hello", sayHello)

	// 创建服务器
	server := &http.Server{
		Addr:         ":1210",
		WriteTimeout: time.Second * 3,
		Handler:      mux,
	}

	// 监听端口并提供服务
	log.Println("starting httpserver at http:localhost:1210")
	log.Fatal(server.ListenAndServe())
}

func sayHello(w http.ResponseWriter, r *http.Request) {
	time.Sleep(1 * time.Second)
	w.Write([]byte("hello hello, this is httpserver"))
}

结合上一小节 服务端实现代码 中,关注方法 mux.HandleFunc("/hello", sayHello)。 如何把 路由规则、处理方法关联起来。

code-snapshot (1).png

开启服务器

Serve 接受 Listener l 传入 连接,为每一个连接创建一个新 goroutine。 服务 goroutine 读取请求并然后调用 srv.Handler 来处理响应他们。

code-snapshot (2).png

处理连接

有了上面两步 注入路由 和 开启服务等待请求后。 事情就简单了,就是拿着请求去匹配路由,调用路由对应方法。 这里由 ServeHTTP 将请求分发, url 匹配路由 后分派给 对应处理程序

code-snapshot (3).png