文档
官方文档:https://godoc.org/github.com/gin-gonic/gin
官方地址:https://github.com/gin-gonic/gin
中文文档:https://gin-gonic.com/zh-cn/docs
Apifox:https://www.apifox.cn
安装
先配置好GOROOT和GOPATH
输入命令:go get github.com/gin-gonic/gin
1.简单示例
//导入包
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//初始化引擎实例
router:=gin.Default()
//注册一个Get请求的方法
router.GET("/", func(context *gin.Context) {
context.String(http.StatusOK,"HelloWorld")
})
router.Run()//默认8080端口 自己指定例如: router.Run(":8888")
}
2.API示例
2.1 GET方式传参
func main() {
// /welcome?firstname=Jane&lastname=Doe
r.GET("/welcome", func(c *gin.Context) {
//获取firstname参数,firstname参数不存在,则使用默认的值 也就是c.DefaultQuery的第二参数值
firstName := c.DefaultQuery("firstname", "abc")
//获取lastname参数,不设置默认值
lastName := c.Query("lastname")
c.String(http.StatusOK, "Hello %s %s", firstName, lastName)
})
}
2.2 POST方式传参
func main() {
r.POST("/formPost", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "k2")
c.JSON(http.StatusOK, gin.H{
"result_code": 1,
"message": message,
"nick": nick,
})
})
}
2.3路由匹配
func main() {
//路由1:匹配/user/xiaoxu 不匹配/user/xiaoxu/123
r.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "you name is "+name)
})
//路由2:匹配/user/xiaoxu/123
r.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)
})
}
路由1和路由2的区别。路由1参数前是":"只匹配/后的内容,如果和比正确的路由多个参数,则无法正确匹配。路由2参数前是 " * "匹配 /及之后的参数
2.3GET和POST方式结合传参
func main() {
r.POST("getAndPost", func(c *gin.Context) {
id := c.Query("id")
userKey := c.Query("user_key")
name := c.PostForm("name")
password := c.PostForm("password")
fmt.Printf("Get方式:id: %s; user_key: %s; Post方式:name: %s; password: %s", id, userKey, name, password)
c.JSON(http.StatusOK, gin.H{
"result_code": 1,
"message": "成功",
"data": 1,
})
})
}