VSCode 搭建Gin
Gin:路由配置和获取参数
Gin:路由抽离与分组
Gin:自定义控制器及控制器继承
Gin:中间件
Gin:文件上传
Gin:Cookie及二级域名共享Cookie
Gin:Session

1. 对路由进行分组

  • 这里使用2组路由,user和department
  • 新建routers文件夹,创建userRouters.go和departmentRouters.go
  • userRouters
package routers

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func UserRoutersInit(router *gin.Engine) {

	userRouter := router.Group("/user")
	userRouter.GET("/addUser", func(c *gin.Context) {
		c.String(http.StatusOK, "添加用户")
	})
	userRouter.GET("/editUser", func(c *gin.Context) {
		c.String(http.StatusOK, "修改用户")
	})
	userRouter.GET("/queryUser", func(c *gin.Context) {
		c.String(http.StatusOK, "查询用户")
	})

}

  • departmentRouters
package routers

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func DeptRoutersInit(router *gin.Engine) {

	deptRouter := router.Group("/dept")
	deptRouter.GET("/addDept", func(c *gin.Context) {
		c.String(http.StatusOK, "添加部门")
	})
	deptRouter.GET("/editDept", func(c *gin.Context) {
		c.String(http.StatusOK, "修改部门")
	})
	deptRouter.GET("/queryDept", func(c *gin.Context) {
		c.String(http.StatusOK, "查询部门")
	})

}

2. 配置 main.go

package main

import (
	"ginDemo2/routers"

	"github.com/gin-gonic/gin"
)

func main() {

	// 创建一个默认的路由引擎
	r := gin.Default()

	// 配置路由
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			// c.JSON:返回 JSON 格式的数据
			"message": "Hello world!",
		})
	})

	// 路由抽离并分组
	routers.UserRoutersInit(r)

	routers.DeptRoutersInit(r)

	// 启动 HTTP 服务,默认在 0.0.0.0:8080 启动服务
	r.Run()

}

3. 启动服务

  • http://localhost:8080/user/editUser
  • http://localhost:8080/user/addUser
  • http://localhost:8080/dept/addDept
  • http://localhost:8080/dept/queryDept