Iris搭建路由模块controller+审计中间件
- 封装NewControllerRoute方法:iris_demo/route/route.go
- 封住NewSignRoute方法,添加自定义中间件:iris_demo/util/route_util.go
- 自定义中间件:iris_demo/middleware/audittrail_middleware.go、iris_demo/middleware/signature_middleware.go
- 定义通用返回值:iris_demo/response/response.go
- 封装baseController,通用controller方法:iris_demo/controller/base_controller.go
- 定义业务controller:iris_demo/controller/user_controller.go
- main方法中初始化controllers:initControllers
完整代码:
https://github.com/ziyifast/ziyifast-code_instruction/tree/main/iris_demo
项目整体结构:
1 定义route/route.go:NewControllerRoute
iris_demo/route/route.go
package routeimport ("github.com/kataras/iris/v12/context"
)var ControllerList = make([]*ControllerRoute, 0)type ControllerRoute struct {RouteName stringControllerObj interface{}ServiceSlice []interface{}MiddlewareSlice []context.HandlerDoneHandleSlice []context.Handler
}func NewControllerRoute(routeName string, controller interface{}, middlewares []context.Handler, doneHandle []context.Handler) {route := &ControllerRoute{RouteName: routeName,ControllerObj: controller,MiddlewareSlice: middlewares,DoneHandleSlice: doneHandle,}ControllerList = append(ControllerList, route)
}
2 定义util/route_util.go:NewSignRoute
定义签名路由:iris_demo/util/route_util.go
package utilimport ("github.com/kataras/iris/v12/context""myTest/demo_home/blom_filter/middleware""myTest/demo_home/blom_filter/route"
)func NewSignRoute(prefix, routeName string, controllerVar interface{}, extraHandler ...context.Handler) {middleWares := []context.Handler{middleware.SignatureMiddleware}if len(extraHandler) > 0 {middleWares = append(middleWares, extraHandler...)}doneHandler := []context.Handler{middleware.AuditTrailMiddleware}route.NewControllerRoute(prefix+routeName, controllerVar, middleWares, doneHandler)
}
3 定义中间件middleware:用于验签、审计等
自定义中间件:i
- ris_demo/middleware/audittrail_middleware.go
- iris_demo/middleware/signature_middleware.go
ris_demo/middleware/audittrail_middleware.go:
package middlewareimport ("github.com/kataras/iris/v12""github.com/ziyifast/log"
)func AuditTrailMiddleware(ctx iris.Context) {log.Infof("audit trail ....")ctx.Next()
}
iris_demo/middleware/signature_middleware.go:
package middlewareimport ("github.com/kataras/iris/v12""github.com/ziyifast/log"
)func SignatureMiddleware(ctx iris.Context) {log.Infof("SignatureMiddleware...do some signature check")ctx.Next()
}
4 定义通用返回值:response.go
iris_demo/response/response.go
package responsetype Code stringvar (ReturnCodeError Code = "0"ReturnCodeSuccess Code = "1"SuccessMsg = "success"SuccessStatus = "success"FailedStatus = "failed"ContentTypeJson = "application/json"
)type JsonResponse struct {Code Code `json:"code"`Msg string `json:"msg"`Content interface{} `json:"data"`
}
5 封装baseController,通用controller方法
封装baseController,通用controller方法:iris_demo/controller/base_controller.go
package controllerimport ("encoding/json""github.com/kataras/iris/v12""github.com/kataras/iris/v12/mvc""github.com/ziyifast/log""myTest/demo_home/iris_demo/response""net/http""strconv"
)type BaseController struct {Ctx iris.Context
}func (c *BaseController) Param(paraName string) string {return c.Ctx.Params().Get(paraName)
}func (c *BaseController) ParamInt64Default(paramName string, defaultValue int64) int64 {return c.Ctx.Params().GetInt64Default(paramName, defaultValue)
}
func (c *BaseController) ParamInt64(paramName string) (int64, error) {return c.Ctx.Params().GetInt64(paramName)
}
func (c *BaseController) ParamInt32Default(paramName string, defaultValue int32) int32 {return c.Ctx.Params().GetInt32Default(paramName, defaultValue)
}
func (c *BaseController) ParamInt32(paramName string) (int32, error) {return c.Ctx.Params().GetInt32(paramName)
}
func (c *BaseController) ParamIntDefault(paramName string, defaultValue int) int {return c.Ctx.Params().GetIntDefault(paramName, defaultValue)
}
func (c *BaseController) ParamInt(paramName string) (int, error) {return c.Ctx.Params().GetInt(paramName)
}func (c *BaseController) ReadParamJson(paramName string, result interface{}) error {paramJson := c.Ctx.FormValue(paramName)if err := json.Unmarshal([]byte(paramJson), result); err != nil {log.Errorf("unmarshal request param[%s] fail, param body [%v] error [%v]", paramName, paramJson, err)return err}return nil
}func (c *BaseController) GetIntFormValue(key string, defaultValue int) int {value := c.Ctx.FormValue(key)if len(value) == 0 {return defaultValue}atoi, err := strconv.Atoi(value)if err != nil {return defaultValue}return atoi
}func (c *BaseController) Message(responseCode response.Code, msg string, content interface{}) mvc.Result {return commonResp(msg, http.StatusOK, responseCode, content)
}
func (c *BaseController) Ok(content interface{}) mvc.Result {return commonResp(response.SuccessMsg, http.StatusOK, response.ReturnCodeSuccess, content)
}func (c *BaseController) OkWithMsg(str string, args ...interface{}) mvc.Result {return commonResp(response.SuccessMsg, http.StatusOK, response.ReturnCodeSuccess, nil)
}func (c *BaseController) Failed(errMsg string, args ...interface{}) mvc.Result {return commonResp(errMsg, http.StatusInternalServerError, response.ReturnCodeError, nil)
}func (c *BaseController) Forbidden() mvc.Result {return commonResp(http.StatusText(http.StatusForbidden), http.StatusForbidden, response.ReturnCodeError, nil)
}func (c *BaseController) BadRequest() mvc.Result {return commonResp(http.StatusText(http.StatusBadRequest), http.StatusBadRequest, response.ReturnCodeError, nil)
}func (c *BaseController) BadRequestWithMsg(errMsg string) mvc.Result {return commonResp(errMsg, http.StatusBadRequest, response.ReturnCodeError, nil)
}func (c *BaseController) SystemInternalError() mvc.Result {return commonResp(http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError, response.ReturnCodeError, nil)
}func (c *BaseController) Unauthorized() mvc.Result {return commonResp(http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized, response.ReturnCodeError, nil)
}func (c *BaseController) SystemInternalErrorWithMsg(errMsg string) mvc.Result {return commonResp(errMsg, http.StatusInternalServerError, response.ReturnCodeError, nil)
}func (c *BaseController) NotFoundError() mvc.Result {return commonResp(http.StatusText(http.StatusNotFound), http.StatusNotFound, response.ReturnCodeError, nil)
}func (c *BaseController) TooManyRequestError() mvc.Result {return commonResp(http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests, response.ReturnCodeError, nil)
}func commonResp(errMsg string, httpCode int, returnCode response.Code, content interface{}) mvc.Response {payload := &response.JsonResponse{Code: returnCode,Msg: errMsg,Content: content,}contentDetail, err := json.Marshal(payload)if err != nil {log.Errorf("marshal json response error %v", err)}return mvc.Response{Code: httpCode,Content: contentDetail,ContentType: response.ContentTypeJson,}
}
6 定义业务Controller:UserController等
定义业务controller:iris_demo/controller/user_controller.go
package controllerimport ("github.com/kataras/iris/v12/mvc""github.com/ziyifast/log""net/http"
)type UserController struct {BaseController
}func (c *UserController) BeforeActivation(b mvc.BeforeActivation) {b.Handle(http.MethodGet, "/smoke", "Smoke")
}func (c *UserController) Smoke() mvc.Result {log.Infof("user controller")defer c.Ctx.Next()return c.Ok("smoke")
}
7 启动iris:initControllers
iris_demo/main.go
package mainimport ("github.com/aobco/log""github.com/kataras/iris/v12""github.com/kataras/iris/v12/mvc""github.com/kataras/iris/v12/sessions""myTest/demo_home/iris_demo/controller""myTest/demo_home/iris_demo/route""myTest/demo_home/iris_demo/util""time"
)var (signaturePrefix = "/yi/anon/"SessionMgr *sessions.Sessions
)func main() {InitControllers()app := iris.New()initMvcHandle(app)app.Listen(":8899")
}
func initSession() {sessionCfg := sessions.Config{Cookie: "test",Expires: time.Duration(60) * time.Minute,}SessionMgr = sessions.New(sessionCfg)
}func initMvcHandle(app *iris.Application) {initSession()for _, v := range route.ControllerList {log.Debugf("routeName:%s middleware:%v doneHandler:%v", v.RouteName, v.MiddlewareSlice, v.DoneHandleSlice)myMvc := mvc.New(app.Party(v.RouteName))myMvc.Router.Use(v.MiddlewareSlice...)myMvc.Router.Done(v.DoneHandleSlice...)myMvc.Register(SessionMgr.Start)myMvc.Handle(v.ControllerObj)}
}func InitControllers() {util.NewSignRoute(signaturePrefix, "user", new(controller.UserController))
}
效果
启动程序,浏览器访问:http://localhost:8899/yi/sign/user/smoke
- 根据我们注册的路由来拼接:prefix+routeName+path
可以看到是:验签 - 业务逻辑 - 审计追踪