gfpool_file.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2017-2020 gf Author(https://github.com/gogf/gf). 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. "errors"
  9. "fmt"
  10. "os"
  11. "time"
  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. // Stat returns the FileInfo structure describing file.
  37. func (f *File) Stat() (os.FileInfo, error) {
  38. if f.stat == nil {
  39. return nil, errors.New("file stat is empty")
  40. }
  41. return f.stat, nil
  42. }
  43. // Close puts the file pointer back to the file pointer pool.
  44. func (f *File) Close() error {
  45. if f.pid == f.pool.id.Val() {
  46. return f.pool.pool.Put(f)
  47. }
  48. return nil
  49. }