github.com/gogf/gf/v2@v2.7.4/os/gfpool/gfpool_file.go (about) 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 7 package gfpool 8 9 import ( 10 "fmt" 11 "os" 12 "time" 13 14 "github.com/gogf/gf/v2/errors/gerror" 15 ) 16 17 // Open creates and returns a file item with given file path, flag and opening permission. 18 // It automatically creates an associated file pointer pool internally when it's called first time. 19 // It retrieves a file item from the file pointer pool after then. 20 func Open(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file *File, err error) { 21 var fpTTL time.Duration 22 if len(ttl) > 0 { 23 fpTTL = ttl[0] 24 } 25 // DO NOT search the path here wasting performance! 26 // Leave following codes just for warning you. 27 // 28 // path, err = gfile.Search(path) 29 // if err != nil { 30 // return nil, err 31 // } 32 pool := pools.GetOrSetFuncLock( 33 fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm), 34 func() interface{} { 35 return New(path, flag, perm, fpTTL) 36 }, 37 ).(*Pool) 38 39 return pool.File() 40 } 41 42 // Get returns a file item with given file path, flag and opening permission. 43 // It retrieves a file item from the file pointer pool after then. 44 func Get(path string, flag int, perm os.FileMode, ttl ...time.Duration) (file *File) { 45 var fpTTL time.Duration 46 if len(ttl) > 0 { 47 fpTTL = ttl[0] 48 } 49 50 f, found := pools.Search(fmt.Sprintf("%s&%d&%d&%d", path, flag, fpTTL, perm)) 51 if !found { 52 return nil 53 } 54 55 fp, _ := f.(*Pool).pool.Get() 56 return fp.(*File) 57 } 58 59 // Stat returns the FileInfo structure describing file. 60 func (f *File) Stat() (os.FileInfo, error) { 61 if f.stat == nil { 62 return nil, gerror.New("file stat is empty") 63 } 64 return f.stat, nil 65 } 66 67 // Close puts the file pointer back to the file pointer pool. 68 func (f *File) Close(close ...bool) error { 69 if len(close) > 0 && close[0] { 70 f.File.Close() 71 } 72 73 if f.pid == f.pool.id.Val() { 74 return f.pool.pool.Put(f) 75 } 76 return nil 77 }