router.template 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package router
  2. import (
  3. "github.com/gin-gonic/gin"
  4. _ "github.com/gin-gonic/gin"
  5. log "github.com/go-admin-team/go-admin-core/logger"
  6. "github.com/go-admin-team/go-admin-core/sdk"
  7. // "github.com/go-admin-team/go-admin-core/sdk/pkg"
  8. "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
  9. jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
  10. common "go-admin/common/middleware"
  11. "os"
  12. )
  13. var (
  14. routerNoCheckRole = make([]func(*gin.RouterGroup), 0)
  15. routerCheckRole = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
  16. )
  17. // InitRouter 路由初始化
  18. func InitRouter() {
  19. var r *gin.Engine
  20. h := sdk.Runtime.GetEngine()
  21. if h == nil {
  22. h = gin.New()
  23. sdk.Runtime.SetEngine(h)
  24. }
  25. switch h.(type) {
  26. case *gin.Engine:
  27. r = h.(*gin.Engine)
  28. default:
  29. log.Fatal("not support other engine")
  30. os.Exit(-1)
  31. }
  32. // the jwt middleware
  33. authMiddleware, err := common.AuthInit()
  34. if err != nil {
  35. log.Fatalf("JWT Init Error, %s", err.Error())
  36. }
  37. // 注册业务路由
  38. InitBusinessRouter(r, authMiddleware)
  39. }
  40. func InitBusinessRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
  41. // 无需认证的路由
  42. noCheckRoleRouter(r)
  43. // 需要认证的路由
  44. checkRoleRouter(r, authMiddleware)
  45. return r
  46. }
  47. // noCheckRoleRouter 无需认证的路由
  48. func noCheckRoleRouter(r *gin.Engine) {
  49. // 可根据业务需求来设置接口版本
  50. v := r.Group("/api/v1")
  51. for _, f := range routerNoCheckRole {
  52. f(v)
  53. }
  54. }
  55. // checkRoleRouter 需要认证的路由
  56. func checkRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
  57. // 可根据业务需求来设置接口版本
  58. v := r.Group("/api/v1")
  59. for _, f := range routerCheckRole {
  60. f(v, authMiddleware)
  61. }
  62. }