I need to generate an unique file name with UUID1.
My current python code is:
uuid.uuid1().hex[:16] // i need 16 chars file name
What could be the golang equivalent?
Thanks!
There isn't a guid or uuid type in the standard library for Go but there are some other ways to do it, like using a third party package such as this; https://godoc.org/code.google.com/p/go-uuid/uuid or https://github.com/nu7hatch/gouuid
import "github.com/nu7hatch/gouuid"
id, err := uuid.NewV4()
This answer has another option as well which makes use of Unix command line utils; Is there a method to generate a UUID with go language though it doesn't seem to perform very well.
I believe you have an impedance mismatch in your problem statement, and your Python code would not work as you expect it should.
As can be deduced by some answers at “Is there a method to generate a UUID with go language”, as well as is clearly described in https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_(date-time_and_MAC_address), UUIDs are very likely to be unique only when taken in full, not in parts, and are not necessarily random at all, especially with the Version 1 actually being rather predictable, as it's based on the date/time and MAC address of the host generating it.
As such, the best approach may be to use something similar to the code in one of the answers to the prior mentioned question, to actually generate a random filename based on crypto/rand
yourself to your own specification, and without the misuse of the libraries not necessarily intended to provide the required randomness for the task at hand.
https://play.golang.org/p/k2V-Mc5Y31e
package main
import (
"crypto/rand"
"fmt"
)
func random_filename_16_char() (s string, err error) {
b := make([]byte, 8)
_, err = rand.Read(b)
if err != nil {
return
}
s = fmt.Sprintf("%x", b)
return
}
func main() {
s, _ := random_filename_16_char()
fmt.Println(s)
}