123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- 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"
- )
- var router iris.Party
- 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)
- router = srv.Party("/api/v1")
- // 登陆,注册
- loginAPI := mvc.New(router.Party("/"))
- loginAPI.Register(userService).Handle(new(controllers.UserController))
- // 用户接口组
- userRouter := router.Party("/user")
- productAPI := mvc.New(userRouter.Party("/product", newJWThandle()))
- productAPI.Register(pService).Handle(new(controllers.ProductController))
- }
|