Java-compatible UUIDs in Go
Java comes with basic built-in UUID support. The java.util.UUID
provides a smattering of UUID functionality. But the documentaiton is scant, and it can be frustrating to try to achieve compatibility with other languages.
Here's how to generate compatible UUIDs with Go. <!-- break -->
Java provides two methods for generating UUIDs: UUID.randomUUID()
and UUID.namedUUIDFromBytes()
. Random UUIDs are not really a problem. Java correctly creates version 4 randomly generated UUIDs.
But the documentation behind UUID.namedUUIDFromBytes()
is ambiguous. Javadoc simply states that it generates "version 3 (name based) UUIDs". Mores pecifically, it's a version 3 UUID with no namespace.
Start with the Go UUID library: code.google.com/p/go-uuid/uuid. From there you can create something like this:
package javauuid
import (
"code.google.com/p/go-uuid/uuid"
)
// Generate a UUID from a byte array.
//
// Generate a Version 3 UUID compatible with Java's
// UUID.namedUUIDFromBytes() method.
//
func NamedUUID(data []byte) *uuid.UUID {
return uuid.NewMD5(nil, data)
}
The key part here is passing in nil
as the namespace. Since Java's UUID library does not handle namespaces at all, we have to mimic this in the call to the Go library.
For more on the Go UUID library, you can browse the generated docs.
NB: I believe that this UUID library is the "official" Google one, but I'm not sure. If you know, please leave a comment. There are many other UUID libraries in Go, but this one seems to be the complete and elegant.