router.go 1.6 KB

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