我想在 Golang 中生成带有扩展名的唯一文件名。非常类似于 ioutil.TempFile,它只需要前缀。
这已在论坛中多次提出https://groups.google.com/forum/#!topic/golang-nuts/PHgye3Hm2_0 Go 似乎非常有意不将该功能添加到 TempFile。
那么建议的处理方法是什么?我应该只复制/粘贴 TempFile 代码并添加后缀参数吗?
最佳答案
更新(2020年:原答案是2015年的)
如 Lax 的 answer 所述,Go 1.11(2018 年 4 月)已将 TempFile
前缀更改为模式。
在commit 191efbc之后从CL 105675看issue 4896
Users of
TempFile
need to be able to supply the suffix, especially when using operating systems that give semantic meaning to the filename extension such as Windows.
Renaming the file to include an extension after the fact is insufficient as it could lead to race conditions.If the string given to
TempFile
includes a "*
", the random string replaces the "*
".For example "
myname.*.bat
" will result in a random filename such as "myname.123456.bat
".If no "
*
' is included the old behavior is retained, and the random digits are appended to the end.If multiple "
*
" are included, the final one is replaced, thus permitting a pathological programmer to create filenames such as "foo*.123456.bat
" but not "foo.123456.*.bat
"
原始答案(2015 年)
Should I just copy/paste the TempFile code and add in a suffix parameter?
这是一种方式。
另一种方法是快速——粗略——实现,如在 this project 中:
// TempFileName generates a temporary filename for use in testing or whatever
func TempFileName(prefix, suffix string) string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return filepath.Join(os.TempDir(), prefix+hex.EncodeToString(randBytes)+suffix)
}
正如下面的 James Henstridge comments,这是一个原始函数:
That function can return file names that already exist, for instance. Such an API should be creating the file by opening it with
O_CREAT | O_EXCL
to ensure that no one else creates the file between deciding on the name and creating the file.
上面那个粗略的函数仅说明了使用 rand.Read()
生成文件名。
但其他检查都在io/ioutil/tempfile.go
中。
3of3 suggests 使用 math.rand
中的函数而不是复制 random number generator in io/ioutil/tempfile.go
。
关于Golang 生成带扩展名的唯一文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005865/