package main
import (
"github.com/gin-gonic/gin"
"net/http"
"fmt"
)
// Gin 路由学习
// https://gin-gonic.com/zh-cn/docs/examples/param-in-path/
// https://gin-gonic.com/zh-cn/docs/examples/grouping-routes/
// RESTfull 路由 GET 函数
func helloWorldGet(c *gin.Context) {
c.String(http.StatusOK, "[gin]Hello, World in GET!")
}
// RESTfull 路由 POST 函数
func helloWorldPost(c *gin.Context) {
c.String(http.StatusOK, "[gin]Hello, World in Post!")
}
// 提取 path 中的参数
func fetchId(c *gin.Context) {
id := c.Param("id")
c.String(http.StatusOK, fmt.Sprintf("id is :%s\n", id))
}
// 组路由
func action1(c *gin.Context) {
c.String(http.StatusOK, "action 1")
}
func action2(c *gin.Context) {
c.String(http.StatusOK, "action 2")
}
func action3(c *gin.Context) {
c.String(http.StatusOK, "action 3")
}
func main() {
router := gin.Default()
// RESTfull 路由
router.GET("/RESTfull", helloWorldGet)
router.POST("/RESTfull", helloWorldPost)
// 不支持正则路由
// 但依然可以 - 提取 path 中的参数
router.GET("/param/:id", fetchId)
// 组路由
group1 := router.Group("/g1")
{
// /g1/action1
group1.GET("/action1", action1)
group1.GET("/action1", action2)
group1.GET("/action1", action3)
}
// 服务启动
router.Run("127.0.0.1:8082")
}