github.com/gogf/gf@v1.16.9/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  	"github.com/gogf/gf/errors/gcode"
    12  	"github.com/gogf/gf/errors/gerror"
    13  	"os"
    14  	"time"
    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  // Stat returns the FileInfo structure describing file.
    43  func (f *File) Stat() (os.FileInfo, error) {
    44  	if f.stat == nil {
    45  		return nil, gerror.NewCode(gcode.CodeInternalError, "file stat is empty")
    46  	}
    47  	return f.stat, nil
    48  }
    49  
    50  // Close puts the file pointer back to the file pointer pool.
    51  func (f *File) Close() error {
    52  	if f.pid == f.pool.id.Val() {
    53  		return f.pool.pool.Put(f)
    54  	}
    55  	return nil
    56  }