gfpool_file.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. "github.com/gogf/gf/errors/gcode"
  10. "github.com/gogf/gf/errors/gerror"
  11. "os"
  12. "time"
  13. )
  14. // Open creates and returns a file item with given file path, flag and opening permission.
  15. // It automatically creates an associated file pointer pool internally when it's called first time.
  16. // It retrieves a file item from the file pointer pool after then.
  17. func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file *File, err error) {
  18. var fpTTL time.Duration
  19. if len(ttl) > 0 {
  20. fpTTL = ttl[0]
  21. }
  22. // DO NOT search the path here wasting performance!
  23. // Leave following codes just for warning you.
  24. //
  25. //path, err = gfile.Search(path)
  26. //if err != nil {
  27. // return nil, err
  28. //}
  29. pool := pools.GetOrSetFuncLock(
  30. fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm),
  31. func() interface{} {
  32. return New(path, flag, perm, fpTTL)
  33. },
  34. ).(*Pool)
  35. return pool.File()
  36. }
  37. // Stat returns the FileInfo structure describing file.
  38. func (f *File) Stat() (os.FileInfo, error) {
  39. if f.stat == nil {
  40. return nil, gerror.NewCode(gcode.CodeInternalError, "file stat is empty")
  41. }
  42. return f.stat, nil
  43. }
  44. // Close puts the file pointer back to the file pointer pool.
  45. func (f *File) Close() error {
  46. if f.pid == f.pool.id.Val() {
  47. return f.pool.pool.Put(f)
  48. }
  49. return nil
  50. }