github.com/lingyao2333/mo-zero@v1.4.1/core/fs/temps.go (about)

     1  package fs
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/lingyao2333/mo-zero/core/hash"
     7  )
     8  
     9  // TempFileWithText creates the temporary file with the given content,
    10  // and returns the opened *os.File instance.
    11  // The file is kept as open, the caller should close the file handle,
    12  // and remove the file by name.
    13  func TempFileWithText(text string) (*os.File, error) {
    14  	tmpfile, err := os.CreateTemp(os.TempDir(), hash.Md5Hex([]byte(text)))
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  
    19  	if err := os.WriteFile(tmpfile.Name(), []byte(text), os.ModeTemporary); err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	return tmpfile, nil
    24  }
    25  
    26  // TempFilenameWithText creates the file with the given content,
    27  // and returns the filename (full path).
    28  // The caller should remove the file after use.
    29  func TempFilenameWithText(text string) (string, error) {
    30  	tmpfile, err := TempFileWithText(text)
    31  	if err != nil {
    32  		return "", err
    33  	}
    34  
    35  	filename := tmpfile.Name()
    36  	if err = tmpfile.Close(); err != nil {
    37  		return "", err
    38  	}
    39  
    40  	return filename, nil
    41  }