temps.go 999 B

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