Gin
Gin 是一个用 Go (Golang) 编写的 web 框架。 它是一个类似于 martini 但拥有更好性能的 API 框架, 由于 httprouter,速度提高了近 40 倍。
Gin拥有多种特性:快速、支持中间件、Crash 处理、JSON 验证、路由组、错误管理、内置渲染、可扩展性等等。
安装
要安装 Gin 软件包,需要先安装 Go 并设置 Go 工作区。
1.下载并安装 gin:
1
| $ go get -u github.com/gin-gonic/gin
|
2.将 gin 引入到代码中:
1
| import "github.com/gin-gonic/gin"
|
3.(可选)如果使用诸如 http.StatusOK
之类的常量,则需要引入 net/http
包:
开始
首先,创建一个名为 example.go
的文件
接下来, 将如下的代码写入 example.go
中:
1 2 3 4 5 6 7 8 9 10 11 12 13
| package main
import "github.com/gin-gonic/gin"
func main() { r := gin.Default() r.GET("/hello", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello Gin", }) }) r.Run("localhost:8001") }
|
然后, 执行 go run helloGin.go
命令来运行代码:
Gin特性示例
抽了四个代表性的示例:
使用 HTTP 方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| func main() {
router := gin.Default()
router.GET("/someGet", getting) router.POST("/somePost", posting) router.PUT("/somePut", putting) router.DELETE("/someDelete", deleting) router.PATCH("/somePatch", patching) router.HEAD("/someHead", head) router.OPTIONS("/someOptions", options)
router.Run() }
func getting(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello Gin", }) }
|
使用中间件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| func main() { r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
authorized := r.Group("/") authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) authorized.POST("/submit", submitEndpoint) authorized.POST("/read", readEndpoint)
testing := authorized.Group("testing") testing.GET("/analytics", analyticsEndpoint) }
r.Run(":8080") }
|
在中间件中使用 Goroutine
当在中间件或 handler 中启动新的 Goroutine 时,不能使用原始的上下文,必须使用只读副本。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| func main() { r := gin.Default()
r.GET("/long_async", func(c *gin.Context) { cCp := c.Copy() go func() { time.Sleep(5 * time.Second)
log.Println("Done! in path " + cCp.Request.URL.Path) }() })
r.GET("/long_sync", func(c *gin.Context) { time.Sleep(5 * time.Second)
log.Println("Done! in path " + c.Request.URL.Path) })
r.Run(":8080") }
|
AsciiJSON
使用 AsciiJSON 生成具有转义的非 ASCII 字符的 ASCII-only JSON。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| func main() { r := gin.Default()
r.GET("/someJSON", func(c *gin.Context) { data := map[string]interface{}{ "lang": "GO语言", "tag": "<br>", }
c.AsciiJSON(http.StatusOK, data) })
r.Run(":8080") }
|
参考资料:
Gin Web Framework