package main import ( "sparrow/pkg/generator" "sparrow/services/knowoapi/controllers" "sparrow/services/knowoapi/model" "sparrow/services/knowoapi/services" jwt "github.com/dgrijalva/jwt-go" jwtmiddleware "github.com/iris-contrib/middleware/jwt" "github.com/kataras/iris" "github.com/kataras/iris/mvc" ) func registerErrors(srv *iris.Application) { srv.OnAnyErrorCode(handleErrors) } func handleErrors(ctx iris.Context) { //logger.Default().Serve(ctx) err := controllers.ErrorResponse{ Code: ctx.GetStatusCode(), Message: ctx.Values().GetStringDefault("reason", "未知错误"), } ctx.JSON(err) } // jwt 中间件配置 func newJWThandle() func(ctx iris.Context) { jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{ ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { return []byte(model.SignedString), nil }, ErrorHandler: func(ctx iris.Context, message string) { ctx.StatusCode(iris.StatusUnauthorized) ctx.Values().Set("reason", message) }, SigningMethod: jwt.SigningMethodHS256, }) return jwtHandler.Serve } // 请求路由 func registerRouters(srv *iris.Application, models *model.All, gen *generator.KeyGenerator) { pService := services.NewProductService(models, gen) userService := services.NewUserService(models, gen) appService := services.NewAppService(models, gen) protocalService := services.NewProtocalService(models) v1router := srv.Party("/api/v1") // 登陆,注册 loginAPI := mvc.New(v1router.Party("/")) loginAPI.Register(userService).Handle(new(controllers.UserController)) // 用户接口组 userRouter := v1router.Party("/user") // product api productAPI := mvc.New(userRouter.Party("/product", newJWThandle())) productAPI.Register(pService).Handle(new(controllers.ProductController)) //application api appAPI := mvc.New(userRouter.Party("/application", newJWThandle())) appAPI.Register(appService).Handle(new(controllers.AppController)) // protocal api protocalAPI := mvc.New(userRouter.Party("/protocal", newJWThandle())) protocalAPI.Register(protocalService).Handle(new(controllers.ProtocalController)) }