temps.go 1006 B

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