路由及路由組
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
//訪問/index的GET請求會走這一條處理邏輯
//獲取信息
r.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "GET",
})
})
//創建某個信息
r.POST("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "POST",
})
})
//更新某個信息
r.PUT("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "PUT",
})
})
//刪除某個信息
r.DELETE("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"method": "DELETE",
})
})
//處理所有的請求方法
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"})
//......
}
c.JSON(http.StatusOK, gin.H{
"method": "Any",
})
})
//沒有路由的頁面
//為沒有配置處理函數的路由添加處理程序,默認情況下它返回404代碼
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"msg" : "zisefeizhu",
})
})
//路由組 多用於區分不同的業務線或APP版本
//將擁有共同URL前綴的路由划分為一個路由組。習慣性一對{}包裹同組的路由,這只是為了看着清晰,你用不用{}包裹功能上沒什么區別
//視頻的首頁和詳細頁
//r.GET("/video/index", func(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{"msg":"/video/index"})
//})
//商城的首頁和詳細頁
r.GET("/shop/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"msg":"/shop/index"})
})
//路由組
//把公用的前綴提取出來,創建一個路由組
videoGroup := r.Group("/video")
{
videoGroup.GET("/index", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"msg":"/video/index"})
})
videoGroup.GET("/xx", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"msg":"/video/xx"})
})
videoGroup.GET("/oo", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"msg":"/video/oo"})
})
}
r.Run(":9090")
}
沒有路由
路由組