gfpool_file.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gfpool
  7. import (
  8. "fmt"
  9. "os"
  10. "time"
  11. "github.com/gogf/gf/v2/errors/gerror"
  12. )
  13. // Open creates and returns a file item with given file path, flag and opening permission.
  14. // It automatically creates an associated file pointer pool internally when it's called first time.
  15. // It retrieves a file item from the file pointer pool after then.
  16. func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file *File, err error) {
  17. var fpTTL time.Duration
  18. if len(ttl) > 0 {
  19. fpTTL = ttl[0]
  20. }
  21. // DO NOT search the path here wasting performance!
  22. // Leave following codes just for warning you.
  23. //
  24. // path, err = gfile.Search(path)
  25. // if err != nil {
  26. // return nil, err
  27. // }
  28. pool := pools.GetOrSetFuncLock(
  29. fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm),
  30. func() interface{} {
  31. return New(path, flag, perm, fpTTL)
  32. },
  33. ).(*Pool)
  34. return pool.File()
  35. }
  36. // Get returns a file item with given file path, flag and opening permission.
  37. // It retrieves a file item from the file pointer pool after then.
  38. func Get(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file *File) {
  39. var fpTTL time.Duration
  40. if len(ttl) > 0 {
  41. fpTTL = ttl[0]
  42. }
  43. f, found := pools.Search(fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm))
  44. if !found {
  45. return nil
  46. }
  47. fp, _ := f.(*Pool).pool.Get()
  48. return fp.(*File)
  49. }
  50. // Stat returns the FileInfo structure describing file.
  51. func (f *File) Stat() (os.FileInfo, error) {
  52. if f.stat == nil {
  53. return nil, gerror.New("file stat is empty")
  54. }
  55. return f.stat, nil
  56. }
  57. // Close puts the file pointer back to the file pointer pool.
  58. func (f *File) Close(close ...bool) error {
  59. if len(close) > 0 && close[0] {
  60. f.File.Close()
  61. }
  62. if f.pid == f.pool.id.Val() {
  63. return f.pool.pool.Put(f)
  64. }
  65. return nil
  66. }