1. 简介
Gin 是一个 go 写的 web 框架,具有高性能的优点。
官方地址:https://github.com/gin-gonic/gin
2. 安装
要安装Gin包,首先需要安装Go并设置Go工作区
1、下载并安装
$ go get -u github.com/gin-gonic/gin
2、在代码中导入它
import "github.com/gin-gonic/gin"
2.1 使用包管理工具Govendor安装
1、go get govendor(安装)
$ go get github.com/kardianos/govendor
2、创建项目文件夹并进入文件夹
mkdir -p GOPATH/src/github.com/myusername/project && cd " $$ cd "$_"
3、初始化项目并添加 gin
$ govendor init
$ govendor fetch github.com/gin-gonic/gin@v1.3
4、创建main.go
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
}
5、运行项目
$ go run main.go
3. 使用示范
3.1 使用 GET, POST, PUT, PATCH, DELETE, OPTIONS
func main() {
// Disable Console Color
// gin.DisableConsoleColor()
// 使用默认中间件创建一个gin路由器
// logger and recovery (crash-free) 中间件
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)
// 默认启动的是 8080端口,也可以自己定义启动端口
router.Run()
// router.Run(":3000") for a hard coded port
}
3.2 获取路径中的参数
func main() {
router := gin.Default()
// 此规则能够匹配/user/john这种格式,但不能匹配/user/ 或 /user这种格式
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// 但是,这个规则既能匹配/user/john/格式也能匹配/user/john/send这种格式
// 如果没有其他路由器匹配/user/john,它将重定向到/user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}
3.3 获取Get参数
func main() {
router := gin.Default()
// 匹配的url格式: /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest")
lastname := c.Query("lastname") // 是 c.Request.URL.Query().Get("lastname") 的简写
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run(":8080")
}
3.4 获取Post参数
func main() {
router := gin.Default()
router.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous") // 此方法可以设置默认值
c.JSON(200, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
})
router.Run(":8080")
}
3.5 Get + Post 混合
示例:
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=manu&message=this_is_great
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}
结果:id: 1234; page: 1; name: manu; message: this_is_great
4. 参考
https://www.jianshu.com/p/98965b3ff638/