Skip to content

Instantly share code, notes, and snippets.

@hidva
Created September 17, 2016 01:43
Show Gist options
  • Save hidva/ca5f6dc9695c60bd9a84d071acc57622 to your computer and use it in GitHub Desktop.
Save hidva/ca5f6dc9695c60bd9a84d071acc57622 to your computer and use it in GitHub Desktop.
Golang 创建一个唯一的文件.
import (
"os"
"github.com/satori/go.uuid"
)
func UniqueFile(dir, prefix string, flags int, perm os.FileMode) (f *os.File, err error) {
unique_file_prefix := dir + "/" + prefix
flags |= os.O_EXCL | os.O_CREATE
GetRandomString := func() string {
return uuid.NewV4().String()
}
for {
unique_file_path := unique_file_prefix + GetRandomString()
f, err = os.OpenFile(unique_file_path, flags, perm)
if os.IsExist(err) {
continue
}
break
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment