Golang Gin 请求参数的获取值 & 路由分组 & 控制器继承

发布时间 2023-11-23 12:42:42作者: 看一百次夜空里的深蓝

一. 请求参数的获取值   动态路由

  1 type User struct {
  2     Username string `form:"username" json:"username"`
  3     Password string `form:"password" json:"password"`
  4     Age      int    `form:"age" json:"age"`
  5 }
  6 
  7 // TestRequestParameter 网页请求携带的参数
  8 func TestRequestParameter() {
  9     router := gin.Default()
 10 
 11     router.SetFuncMap(
 12         template.FuncMap{
 13             "UnixToTime": UnixToTime,
 14             "Println":    Println,
 15         })
 16     router.LoadHTMLGlob("templates/**/*")
 17     router.Static("/static", "./static")
 18 
 19     router.GET("/user", func(c *gin.Context) {
 20         c.HTML(http.StatusOK, "default/user.html", gin.H{})
 21     })
 22 
 23     // 获取get过来的参数
 24     router.GET("/", func(c *gin.Context) {
 25         username := c.Query("username")
 26         age := c.Query("age")
 27         page := c.DefaultQuery("page", "1")
 28 
 29         c.JSON(http.StatusOK, gin.H{
 30             "username": username,
 31             "age":      age,
 32             "page":     page,
 33         })
 34 
 35     })
 36 
 37     // 获取表单post过来的数据
 38     router.POST("/doAddUser", func(c *gin.Context) {
 39         username := c.PostForm("username")
 40         password := c.PostForm("password")
 41         age := c.DefaultPostForm("age", "20")
 42 
 43         c.JSON(http.StatusOK, gin.H{
 44             "username": username,
 45             "password": password,
 46             "age":      age,
 47         })
 48     })
 49 
 50     // 获取Get传递数据绑定到结构体
 51     // http://localhost:8080/getUser?username=root&password=123456
 52     router.GET("/getUser", func(c *gin.Context) {
 53         user := &User{}
 54         if err := c.ShouldBind(user); err == nil {
 55             c.JSON(http.StatusOK, user)
 56         } else {
 57             c.JSON(http.StatusOK, gin.H{
 58                 "err": err.Error(),
 59             })
 60         }
 61     })
 62 
 63     // 获取POST传递数据绑定到结构体
 64     router.POST("/doAddUser2", func(c *gin.Context) {
 65         user := &User{}
 66         if err := c.ShouldBind(user); err == nil {
 67             c.JSON(http.StatusOK, user)
 68         } else {
 69             c.JSON(http.StatusOK, gin.H{
 70                 "err": err.Error(),
 71             })
 72         }
 73     })
 74 
 75     // 获取POST传递xml数据绑定到结构体
 76     type Article struct {
 77         Title   string `xml:"title"`
 78         Content string `xml:"content"`
 79     }
 80     router.POST("/xml", func(c *gin.Context) {
 81         b, _ := c.GetRawData() // 从c.Request,Body读取请求数据
 82 
 83         art := &Article{}
 84         if err := xml.Unmarshal(b, art); err == nil {
 85             c.JSON(http.StatusOK, art)
 86         } else {
 87             c.JSON(http.StatusOK, gin.H{
 88                 "msg": err.Error(),
 89             })
 90         }
 91 
 92     })
 93 
 94     // 动态路由
 95     router.GET("/list/:cid/:eid", func(c *gin.Context) {
 96         // http://localhost:8080/list/80/10
 97         cid := c.Param("cid")
 98         eid := c.Param("cid")
 99 
100         c.String(http.StatusOK, "cid=%v,eid=%v", cid, eid)
101     })
102 
103     router.Run("0.0.0.0:8080")
104 }

 

二. 路由分组

 1 // 路由分组
 2 func TestRouterGroup() {
 3     router := gin.Default()
 4 
 5     router.SetFuncMap(
 6         template.FuncMap{
 7             "UnixToTime": UnixToTime,
 8             "Println":    Println,
 9         })
10     router.LoadHTMLGlob("templates/**/*")
11     router.Static("/static", "./static")
12 
13     defaultRouters := router.Group("/")
14     {
15         // http://localhost:8080/
16         defaultRouters.GET("/", func(c *gin.Context) {
17             c.String(http.StatusOK, "首页")
18         })
19 
20         // http://localhost:8080/news
21         defaultRouters.GET("/news", func(c *gin.Context) {
22             c.String(http.StatusOK, "新闻")
23         })
24     }
25 
26     // 也可以单独列出来,放到独立文件中去
27     routers.AdminRouters(router)
28     routers.ApiRouters(router)
29 
30     router.Run("0.0.0.0:8080")
31 
32 }
func AdminRouters(r *gin.Engine) {
    adminRouters := r.Group("/admin")
    {
        // http://localhost:8080/admin/
        adminRouters.GET("/", func(c *gin.Context) {
            c.String(http.StatusOK, "后台首页")
        })

        // 通过控制器去控制路由更方便,因为控制器可以继承
        // http://localhost:8080/admin/user
        adminRouters.GET("/user", admin.UserControl{}.Index)

        // http://localhost:8080/admin/user/add
        adminRouters.GET("/user/add", admin.UserControl{}.Add)

        // http://localhost:8080/admin/user/edit
        adminRouters.GET("/user/edit", admin.UserControl{}.Edit)

        // http://localhost:8080/admin/article
        adminRouters.GET("/article", admin.ArticleControl{}.Index)
    }
}

 

三. 控制器继承

type BaseControl struct{}

func (b BaseControl) Success(c *gin.Context) {
    c.String(http.StatusOK, "Success")
}

func (b BaseControl) Fail(c *gin.Context) {
    c.String(http.StatusBadRequest, "Fail")
}


type UserControl struct {
    controls.BaseControl
}

func (con UserControl) Index(c *gin.Context) {
    c.String(http.StatusOK, "用户列表-首页")
}

func (con UserControl) Add(c *gin.Context) {
    c.String(http.StatusOK, "添加用户")
}

func (con UserControl) Edit(c *gin.Context) {
    c.String(http.StatusOK, "编辑用户")
}

func (con UserControl) Delete(c *gin.Context) {
    c.String(http.StatusOK, "删除用户")
}