tree.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package service
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "jylua-api/internal/dao"
  6. "jylua-api/internal/model"
  7. "sync"
  8. )
  9. type (
  10. luaPathTree struct {
  11. mTree map[int]*pathObj
  12. mLock *sync.Mutex
  13. }
  14. pathObj struct {
  15. Path string
  16. Pid int
  17. BScan bool
  18. }
  19. )
  20. var (
  21. JyLuaPathTree = &luaPathTree{
  22. mTree: map[int]*pathObj{},
  23. mLock: &sync.Mutex{},
  24. }
  25. )
  26. func (tree *luaPathTree) GetPath(gid int, path string, force bool) string {
  27. tree.mLock.Lock()
  28. defer tree.mLock.Unlock()
  29. ctx := context.Background()
  30. if len(tree.mTree) == 0 || force {
  31. //初始化
  32. var group []*model.JyapiGroup
  33. err := dao.JyapiGroup.Ctx(ctx).Where("status=1").Order("pid ASC").Scan(&group)
  34. if err == nil {
  35. for _, v1 := range group {
  36. tree.mTree[v1.Id] = &pathObj{v1.Path, v1.Pid, false}
  37. }
  38. for _, v1 := range group {
  39. pid := v1.Pid
  40. for {
  41. if p, ok := tree.mTree[pid]; ok {
  42. tree.mTree[v1.Id].Path = p.Path + tree.mTree[v1.Id].Path
  43. pid = p.Pid
  44. if p.BScan {
  45. tree.mTree[v1.Id].BScan = true
  46. break
  47. }
  48. } else {
  49. tree.mTree[v1.Id].BScan = true
  50. break
  51. }
  52. }
  53. }
  54. } else {
  55. g.Log().Error(ctx, err)
  56. }
  57. }
  58. var fPatch string
  59. if pObj, ok := tree.mTree[gid]; ok {
  60. fPatch = pObj.Path
  61. }
  62. return fPatch + path
  63. }