缘由
大家好,做过项目的都知道“脚手架”的概念,即每个系统都需要有一个基础的脚手架,脚手架要具备一些基础的功能:http服务、日志模块、配置读取、异常处理、RPC等等。Java有Spring框架,非常强大,Go也有很多开源的框架。大厂有自己微服务架构,对于我们个人或者小团队而言,可以基于 Gin 实现一个,不用每次从零开始。
Gin概述
Gin 是一个用 Go(Golang)编写的 HTTP Web 框架。它采用了类似 Martini 的 API,但性能比 Martini 快 40 倍。
Github地址:
https://github.com/gin-gonic/gin
特征
- Zero allocation router
- Speed
- Middleware support
- Crash-free
- JSON validation
- Route grouping
- Error management
- Built-in rendering
- Extensible
快速入门
- 准备 Go 开发环境
- 安装 Gin
go get -u github.com/gin-gonic/gin
- 创建目录:
mkdir gin-demo
- 创建文件: main.go (可通过IDE或者文本编辑器创建)
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
// 初始化
g := gin.Default()
// 添加 http get 处理
g.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "hello world!",
})
})
// 启动服务
g.Run()
}
- 项目 gin-demo 目录下,执行 go mod init gin-demo 和 go mod tidy 命令完成依赖导入,将自动生产 go.mod 、go.sum 文件。
> tree
.
├── go.mod
├── go.sum
└── main.go
- 运行 main.go
> go run 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 /hello --> 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] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
- 访问URL:
此时,Web Server 监听 8080 端口,访问
http://localhost:8080/hello, 则会响应:
> curl http://localhost:8080/hello
{"message":"hello world!"}
总结
Gin 的入门很简单,简单几行代码就可以启动一个 Web Server,并且还有非常完善的组件等,但如果作为一个服务端应用,还远远不够,后续逐步添加。