介绍
Gin 是一个用 Go (Golang) 编写的 Web 框架。 它具有类似 martini 的 API,性能要好得多,多亏了 httprouter,速度提高了 40 倍。 如果您需要性能和良好的生产力,您一定会喜欢 Gin。
安装
go get -u github.com/gin-gonic/gin
快速开始
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() // 监听并在 0.0.0.0:8080 上启动服务
}
接受请求参数
公共部分
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
//调用方法
router.Run(":8080")
}
get请求
获取路径上数据(post一样)
使用gin.Context.Query("参数名")获取
func main() {
router := gin.Default()
testGetUrl(router)
router.Run(":8080")
}
func testGetUrl(router *gin.Engine) {
router.GET("/getUrl", func(c *gin.Context) {
// 获取参数值
name := c.Query("name")
age := c.Query("age")
// 返回响应
c.JSON(http.StatusOK, gin.H{
"name": name,
"age": age,
})
})
}
获取路由参数(post一样)
package main
import (
"github.com/gin-gonic/gin"
"io"
"net/http"
"net/url"
"os"
)
func main() {
router := gin.Default()
testRouteParams(router)
router.Run(":8080")
}
func testRouteParams(router *gin.Engine) {
router.GET("/routeParams/:name/:age", func(c *gin.Context) {
// 获取参数值
name := c.Param("name")
age := c.Param("age")
// 返回响应
c.JSON(http.StatusOK, gin.H{
"name": name,
"age": age,
})
})
}
获取cookie(post一样)
pack