You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/fs/temps.go

42 lines
991 B
Go

4 years ago
package fs
import (
"os"
"github.com/zeromicro/go-zero/core/hash"
4 years ago
)
// TempFileWithText creates the temporary file with the given content,
// and returns the opened *os.File instance.
// The file is kept as open, the caller should close the file handle,
// and remove the file by name.
func TempFileWithText(text string) (*os.File, error) {
2 years ago
tmpFile, err := os.CreateTemp(os.TempDir(), hash.Md5Hex([]byte(text)))
4 years ago
if err != nil {
return nil, err
}
2 years ago
if err := os.WriteFile(tmpFile.Name(), []byte(text), os.ModeTemporary); err != nil {
4 years ago
return nil, err
}
2 years ago
return tmpFile, nil
4 years ago
}
// TempFilenameWithText creates the file with the given content,
// and returns the filename (full path).
// The caller should remove the file after use.
func TempFilenameWithText(text string) (string, error) {
2 years ago
tmpFile, err := TempFileWithText(text)
4 years ago
if err != nil {
return "", err
}
2 years ago
filename := tmpFile.Name()
if err = tmpFile.Close(); err != nil {
4 years ago
return "", err
}
return filename, nil
}