路由
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// gin.Context,封装了request和response
func main() {
r := gin.Default()
r.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK,gin.H{
"method":"GET请求",
})
})
// ......
// any:请求方法大集合
r.Any("/user", func(c *gin.Context) {
switch c.Request.Method {
case "GET":
c.JSON(http.StatusOK,gin.H{"method":"GET"})
case http.MethodPost:
c.JSON(http.StatusOK,gin.H{"method":"POST"})
// .......
}
})
// 访问一个不存在的路径
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound,gin.H{"msg":"heihei"})
})
r.Run()
}
定义路由组 (加前缀)
多用于区分不同的业务线或API的版本
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
// gin.Context,封装了request和response
func main() {
r := gin.Default()
// 视频的首页和详情页
//r.GET("/video/index", func(c *gin.Context) {
// c.JSON(http.StatusOK,gin.H{"msg":"/video/index"})
//})
//r.GET("/video/user", func(c *gin.Context) {
// c.JSON(http.StatusOK,gin.H{"msg":"/video/index"})
//})
//r.GET("/video/part", func(c *gin.Context) {
// c.JSON(http.StatusOK,gin.H{"msg":"/video/index"})
//})
// 把公用的前缀提取出来,创建一个路由组
videoGroup :=r.Group("/video")
{
videoGroup.GET("index", func(c *gin.Context) {
c.JSON(http.StatusOK,gin.H{"msg":"/video/index"})
})
videoGroup.GET("/user", func(c *gin.Context) {
c.JSON(http.StatusOK,gin.H{"msg":"/video/user"})
})
}
// 视频的首页和详情页
//r.GET("/shop/index", func(c *gin.Context) {
// c.JSON(http.StatusOK,gin.H{"msg":"/shop/index"})
//})
//r.Run()
}