启动流程分析
启动服务
服务源码
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
engine := gin.Default()
// 注册路由并设置一个匿名的 handlers,返回 JSON 格式数据
engine.GET("/", func(ctx *gin.Context) {
ctx.JSON(200, gin.H{
"msg": "请求成功",
})
})
// 启动服务,并监听端口 9090
// 不填默认监听 0.0.0.0:8080
_ = engine.Run(":9090")
}
启动输出
> go run main.go
Alias tip: gor main.go
[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET / --> main.main.func1 (3 handlers)
[GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.
Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details.
[GIN-debug] Listening and serving HTTP on :9090
[GIN] 2023/02/25 - 13:53:44 | 200 | 24.987µs | 127.0.0.1 | GET "/"
代码分析
import
在引入Gin
框架时,包内相关的init()
方法都会被执行
下面两个init
方法:
github.com/gin-gonic/gin/context_appengine.go
github.com/gin-gonic/gin/mode.go
(1)github.com/gin-gonic/gin/context_appengine.go
源码:https://github.com/gin-gonic/gin/blob/v1.9.0/context_appengine.go#L10-L12
设置 defaultPlatform
为 PlatformGoogleAppEngine
源码:https://github.com/gin-gonic/gin/blob/v1.9.0/gin.go#L72-L80
// Trusted platforms
const (
// PlatformGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr
// for determining the client's IP
PlatformGoogleAppEngine = "X-Appengine-Remote-Addr"
// PlatformCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining
// the client's IP
PlatformCloudflare = "CF-Connecting-IP"
)
(2)github.com/gin-gonic/gin/mode.go
源码:https://github.com/gin-gonic/gin/blob/v1.9.0/mode.go#L51-L54
设置服务的运行模式,默认是 DebugMode
分别有三种模式:DebugMode=0 (开发模式)、releaseCode=1 (生产模式)、testCode=2 (测试模式)
源码:https://github.com/gin-gonic/gin/blob/v1.9.0/mode.go#L15-L25