init_router.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package router
  2. import (
  3. "Medical_OAuth/common/middleware"
  4. handler2 "Medical_OAuth/common/middleware/handler"
  5. "github.com/gin-gonic/gin"
  6. swaggerfiles "github.com/swaggo/files"
  7. ginSwagger "github.com/swaggo/gin-swagger"
  8. jwt "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
  9. "gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
  10. "os"
  11. log "gogs.baozhida.cn/zoie/OAuth-core/logger"
  12. "gogs.baozhida.cn/zoie/OAuth-core/sdk"
  13. )
  14. // InitRouter 路由初始化,不要怀疑,这里用到了
  15. func InitRouter() {
  16. var r *gin.Engine
  17. h := sdk.Runtime.GetEngine()
  18. if h == nil {
  19. log.Fatal("not found engine...")
  20. os.Exit(-1)
  21. }
  22. switch h.(type) {
  23. case *gin.Engine:
  24. r = h.(*gin.Engine)
  25. default:
  26. log.Fatal("not support other engine")
  27. os.Exit(-1)
  28. }
  29. // the jwt middleware
  30. authMiddleware, err := middleware.AuthInit()
  31. if err != nil {
  32. log.Fatalf("JWT Init Error, %s", err.Error())
  33. }
  34. // 注册系统路由
  35. InitSysRouter(r, authMiddleware)
  36. }
  37. func InitSysRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.RouterGroup {
  38. g := r.Group("")
  39. // 静态文件
  40. // sysStaticFileRouter(g)
  41. // swagger;注意:生产环境可以注释掉
  42. if config.ApplicationConfig.Mode != "prod" {
  43. sysSwaggerRouter(g)
  44. }
  45. // 需要认证
  46. sysCheckRoleRouterInit(g, authMiddleware)
  47. return g
  48. }
  49. func sysSwaggerRouter(r *gin.RouterGroup) {
  50. //r.GET("/swagger/admin/*any", ginSwagger.WrapHandler(swaggerfiles.NewHandler(), ginSwagger.InstanceName("admin")))
  51. //r.GET("/swagger/*any", func(c *gin.Context) {
  52. // ginSwagger.DisablingWrapHandler(swaggerfiles.Handler, "SWAGGER")(c)
  53. //})
  54. r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
  55. }
  56. func sysCheckRoleRouterInit(r *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
  57. v1 := r.Group("/api/")
  58. {
  59. v1.POST("/login", authMiddleware.LoginHandler)
  60. // Refresh time can be longer than token timeout
  61. v1.GET("/refresh_token", authMiddleware.RefreshHandler)
  62. }
  63. for _, f := range routerCheckRole {
  64. f(v1, authMiddleware)
  65. }
  66. registerBaseRouter(v1, authMiddleware)
  67. }
  68. func registerBaseRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware) {
  69. v1auth := v1.Group("").Use(authMiddleware.MiddlewareFunc()).Use(middleware.AuthCheckRole())
  70. {
  71. v1auth.POST("/logout", handler2.LogOut)
  72. }
  73. }