#### **1 控制器创建** * 项目根目录下 创建文件夹 controllers * 如下 ![](https://img.kancloud.cn/66/53/665380167abcbc31da07f123d26c2a14_488x276.png) **api.go** ~~~ package routes import ( "github.com/gin-gonic/gin" "learn_gin/controllers/api" ) func Api(r *gin.Engine) { route := r.Group("/api") route.GET("/login", api.Login) } ~~~ **loginController.go** ~~~ package api import "github.com/gin-gonic/gin" func Login(ctx *gin.Context) { } ~~~ ### **2 控制器继承** * golang中的继承主要靠结构体来实现 baseController.go ~~~ package api import ( "github.com/gin-gonic/gin" "net/http" ) type BaseController struct { } func(base BaseController) successMsg(ctx *gin.Context) { ctx.String(http.StatusOK,"success") } func(base BaseController) errorMsg(ctx *gin.Context) { ctx.String(http.StatusInternalServerError,"error") } ~~~ userControllerController.go ~~~ package api import "github.com/gin-gonic/gin" type UserController struct { //这里用来实现继承 BaseController } func(user UserController) List(ctx *gin.Context) { user.errorMsg(ctx) } func(user UserController) Insert(ctx *gin.Context){ user.successMsg(ctx) } ~~~