gin
Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API, but with performance up to 40 times faster than Martini.
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
Quick Start
Installation
$ go get -u github.com/gin-gonic/gin
Import it in your code:
import "github.com/gin-gonic/gin"
(Optional) Import net/http
. This is required for example if using constants such as http.StatusOK
.
import "net/http"
特性
- 快速:路由不使用反射,基于 Radix 树,内存占用少。
- 中间件:HTTP 请求,可先经过一系列中间件处理,例如:Logger,Authorization,GZIP 等。这个特性和 NodeJs 的
Koa
框架很像。中间件机制也极大地提高了框架的可扩展性。 - 异常处理:服务始终可用,不会宕机。Gin 可以捕获 panic,并恢复。而且有极为便利的机制处理 HTTP 请求过程中发生的错误。
- JSON:Gin 可以解析并验证请求的 JSON。这个特性对
Restful API
的开发尤其有用。 - 路由分组:例如将需要授权和不需要授权的 API 分组,不同版本的 API 分组。而且分组可嵌套,且性能不受影响。
- 渲染内置:原生支持 JSON,XML 和 HTML 的渲染。
路由
路径参数
/user/:name/*role
,:
代表动态参数,*
代表可选。
// 匹配 /user/geektutu
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// $ curl http://localhost:9999/user/geektutu
// Hello geektutu
查询参数
// 匹配users?name=xxx&role=xxx,role可选
r.GET("/users", func(c *gin.Context) {
name := c.Query("name") // 获取查询参数
role := c.DefaultQuery("role", "teacher") // 获取并设置查询默认参数
c.String(http.StatusOK, "%s is a %s", name, role)
})
// $ curl "http://localhost:9999/users?name=Tom&role=student"
// Tom is a student
获取 POST 参数
// POST
r.POST("/form", func(c *gin.Context) {
username := c.PostForm("username")
password := c.DefaultPostForm("password", "000000") // 可设置默认值
c.JSON(http.StatusOK, gin.H{
"username": username,
"password": password,
})
})
// $ curl http://localhost:9999/form -X POST -d 'username=geektutu&password=1234'
// {"password":"1234","username":"geektutu"}