Router.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package router
  2. import (
  3. "demo/data/dao"
  4. "demo/data/domain"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "strings"
  8. "time"
  9. )
  10. var PathRouterMap = make(map[string]domain.BackAuthority)
  11. var PathIRouterMap = make(map[string]gin.IRoutes)
  12. const Prefix = "/api"
  13. func InitRouter(apiGroup *gin.RouterGroup, Router *gin.Engine) {
  14. apiGroup.Use(LogInterceptor())
  15. apiGroup.Use(LogInterceptor())
  16. //用户,包含用户后台
  17. UserRouth(apiGroup)
  18. //文章详情页
  19. DetailRouter(apiGroup)
  20. //文件上传下载
  21. FileRouter(apiGroup)
  22. //测试
  23. TestRouth(apiGroup)
  24. //订单,支付
  25. OrderRouter(apiGroup)
  26. //-------------------
  27. //后台管理系统
  28. BackRouter(apiGroup)
  29. //获取全部路由
  30. }
  31. func PushRouter(api *gin.RouterGroup, method, path string, handlerFunc gin.HandlerFunc) {
  32. var iRouter gin.IRoutes
  33. switch method {
  34. case "GET":
  35. iRouter = api.GET(path, handlerFunc)
  36. break
  37. case "POST":
  38. iRouter = api.POST(path, handlerFunc)
  39. break
  40. case "PUT":
  41. iRouter = api.PUT(path, handlerFunc)
  42. break
  43. case "DELETE":
  44. iRouter = api.DELETE(path, handlerFunc)
  45. break
  46. case "PATCH":
  47. iRouter = api.PATCH(path, handlerFunc)
  48. break
  49. case "HEAD":
  50. iRouter = api.HEAD(path, handlerFunc)
  51. break
  52. default:
  53. iRouter = api.Any(path, handlerFunc)
  54. }
  55. fmt.Println(api.BasePath() + path)
  56. key := api.BasePath() + path
  57. if strings.HasPrefix(key, Prefix) {
  58. key = key[len(Prefix):]
  59. }
  60. PathIRouterMap[key] = iRouter
  61. }
  62. func InitAuthority(Router *gin.Engine) {
  63. //查询数据库有的权限
  64. List := dao.GetListAuthorityAll()
  65. pathMap := make(map[string]domain.BackAuthority)
  66. for i := range List {
  67. pathMap[List[i].AuthorityPath] = List[i]
  68. }
  69. routes := Router.Routes()
  70. var insertRouter = make([]*domain.BackAuthority, 0)
  71. for i := range routes {
  72. method := Router.Routes()[i].Method
  73. path := Router.Routes()[i].Path
  74. if strings.HasPrefix(path, Prefix) {
  75. path = path[len(Prefix):]
  76. }
  77. if _, ok := pathMap[path]; !ok {
  78. insertRouter = append(insertRouter, &domain.BackAuthority{
  79. AuthorityPath: path,
  80. Method: method,
  81. State: "1",
  82. AuthorityVerification: "",
  83. CreateTime: time.Now()})
  84. }
  85. }
  86. dao.AddAllListAuthorityAll(insertRouter)
  87. for i := range insertRouter {
  88. pathMap[insertRouter[i].AuthorityPath] = *insertRouter[i]
  89. }
  90. PathRouterMap = pathMap
  91. for s := range PathIRouterMap {
  92. AddUseInterceptor(PathIRouterMap[s], pathMap[s].AuthorityVerification)
  93. }
  94. }