router.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "sparrow/pkg/generator"
  4. "sparrow/services/knowoapi/controllers"
  5. "sparrow/services/knowoapi/model"
  6. "sparrow/services/knowoapi/services"
  7. jwt "github.com/dgrijalva/jwt-go"
  8. jwtmiddleware "github.com/iris-contrib/middleware/jwt"
  9. "github.com/kataras/iris"
  10. "github.com/kataras/iris/mvc"
  11. )
  12. func registerErrors(srv *iris.Application) {
  13. srv.OnAnyErrorCode(handleErrors)
  14. }
  15. func handleErrors(ctx iris.Context) {
  16. //logger.Default().Serve(ctx)
  17. err := controllers.ErrorResponse{
  18. Code: ctx.GetStatusCode(),
  19. Message: ctx.Values().GetStringDefault("reason", "未知错误"),
  20. }
  21. ctx.JSON(err)
  22. }
  23. // jwt 中间件配置
  24. func newJWThandle() func(ctx iris.Context) {
  25. jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
  26. ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
  27. return []byte(model.SignedString), nil
  28. },
  29. ErrorHandler: func(ctx iris.Context, message string) {
  30. ctx.StatusCode(iris.StatusUnauthorized)
  31. ctx.Values().Set("reason", message)
  32. },
  33. SigningMethod: jwt.SigningMethodHS256,
  34. })
  35. return jwtHandler.Serve
  36. }
  37. // 请求路由
  38. func registerRouters(srv *iris.Application, models *model.All, gen *generator.KeyGenerator) {
  39. pService := services.NewProductService(models, gen)
  40. userService := services.NewUserService(models, gen)
  41. appService := services.NewAppService(models, gen)
  42. protocalService := services.NewProtocalService(models)
  43. v1router := srv.Party("/api/v1")
  44. // 登陆,注册
  45. loginAPI := mvc.New(v1router.Party("/"))
  46. loginAPI.Register(userService).Handle(new(controllers.UserController))
  47. // 用户接口组
  48. userRouter := v1router.Party("/user")
  49. // product api
  50. productAPI := mvc.New(userRouter.Party("/product", newJWThandle()))
  51. productAPI.Register(pService).Handle(new(controllers.ProductController))
  52. //application api
  53. appAPI := mvc.New(userRouter.Party("/application", newJWThandle()))
  54. appAPI.Register(appService).Handle(new(controllers.AppController))
  55. // protocal api
  56. protocalAPI := mvc.New(userRouter.Party("/protocal", newJWThandle()))
  57. protocalAPI.Register(protocalService).Handle(new(controllers.ProtocalController))
  58. }