Go: gin框架使用的内置 net/http 库解析
最近在学习 Gin 框架的一些知识,了解到其服务端处理 http 请求以及 底层TCP连接的模块使用的是 Go 内置的 net/http库,于是乎对这个库的 http .Server 模块展开了一下了解,通过对这个单独结构的了解也可以大致窥探整个go的net/http库的全貌。最后,我做了一份简单的思维导图放在后面。
主函数大致逻辑如下:
func main() {
// 创建engine结构
core := gin.New()
server := &http.Server{
Handler: core,
Addr: ":8888",
}
// 这个goroutine是启动服务的goroutine
go func() {
server.ListenAndServe()
}()
// 优雅退出的实现
// 当前的goroutine等待信号量
quit := make(chan os.Signal)
// 监控信号:SIGINT, SIGTERM, SIGQUIT
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
// 这里会阻塞当前goroutine等待信号
<-quit
// 调用Server.Shutdown graceful结束
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(timeoutCtx); err != nil {
log.Fatal("Server Shutdown:", err)
}
}
服务端思维导图,部分还有待补充,若有错误欢迎指正。(有需要清晰的图或者原文件的可以私信我)