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