google / uuid Goto Github PK
View Code? Open in Web Editor NEWGo package for UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
License: BSD 3-Clause "New" or "Revised" License
Go package for UUIDs based on RFC 4122 and DCE 1.1: Authentication and Security Services.
License: BSD 3-Clause "New" or "Revised" License
Hi, could someone confirm if my understanding of this sentence is correct?
"One loss due to this change is the ability to represent an invalid UUID (vs a NIL UUID)."
This is saying that it's not possible to represent an invalid UUID with the google/uuid
library because it is a strict 16-byte array rather than a byte slice? When/why would I want to be able to represent invalid UUIDs, for testing?
Thank you!
Is there any function to get []byte from a UUID instance, or I should write the code as below?
func getBytes(u uuid.UUID) []byte {
b := make([]byte, 16)
for i := range b {
b[i] = u[i]
}
return b
}
I was reading through the code for Parse and I noticed that there is no validation on the first and last characters of the uuid-to-parse when the length of the input is 38 characters:
Lines 38 to 61 in 16ca3ea
I would expect there to be a check that s[0] == '{' && s[37] == '}'
rather than simply ignoring those two characters. I am happy to send a PR if requested, it's a simple change. I am just verifying that this loose behavior is not actually desired.
(fwiw, it means that parsing something like a01234567-abcd-cdef-abcd-012345678901a
would be parsed without an error, even though it has extra characters at the beginning and end. That's quite unexpected IMO.)
it is possible?
Hello,
I've just added a dependency to this project in a bazel compiled system and it was a bit clunky with no BUILD file around.
My current dependency looks like this:
new_git_repository(
name = "google_uuid",
build_file_content = """
load("@io_bazel_rules_go//go:def.bzl", "go_prefix")
load("@io_bazel_rules_go//go:def.bzl", "go_library")
go_prefix("github.com/google/uuid")
go_library(
name = "go_default_library",
srcs = glob([".go"], exclude=["_test.go"]),
deps = [
],
visibility = ["//visibility:public"],
)
""",
tag = "0.2",
remote = "https://github.com/google/uuid",
)
It would be fairly simple to add a BUILD file - if you are ok with that I can just send a pull request (and simplify my dependencies ;-) ).
executor failed running [/bin/sh -c go install github.com/google/[email protected]]: exit code: 1
please give me some solution for same
./json.go:28: multiple-value Parse() in single-value context
uu, err := Parse(string(data))
if err != nil {
I am working on a legacy app that used UUID v4 as its authentication key. Is that secure? (Some implementations, like python3's are secure, meanwhile others aren't)
Moving the entire app to crytpo/rand would be way too much.
When I first encountered the ParseBytes
function I was very surprised that it wasn't meant to parse the raw 16 bytes of a uuid, but instead was meant to parse hexadecimal data. I suspect other users of the library will have the same reaction. It turned out that what I actually was looking for was FromBytes
.
I realize that it's useful to have a hexadecimal byte-parsing function for performance reasons because it avoids copying data around, but if I hadn't checked the docs I might not have realized I had the wrong function until I received an error from it.
I propose that one of two actions be taken:
ParseBytes
to ParseHexBytes
to make its intention more clearParseBytes
to include handling for 16-byte inputs that are then fed into UnmarshalBinary
The SQL Value() gives a string representation of UUID, if this is unindexed data this may make little difference in the performance of the data but where this is either an index or even the PK this not efficient storage. Here's one of many articles on it.
This could either have a breaking change and make this provide a []byte type. If there is some more dominant SQL DB being targeted which does not benefit from this, then we could minimally have a BytesValuer() function to return a Valuer which does do this.
Does an "Equals(uuid1,uuid2)" method actually exists? It's not so fast comparing uuid's by parsing two values in string and then comparing then by '=='.
In order to use Go Dep effectively with semver, please release or tag a new version. Using revisions with many open source project dependencies makes Go Dep much less convenient. The latest version is roughly 1 year and 22 commits in the past thus I could argue a new version is likely. It also seems lately new features were thus further strengthen the idea to bump the version.
Seems like the repo hasn't been tended to in a while - are there any plans to make a v1 release as mentioned in the readme?
Hey 👋🏼
I was curious about why uuid.New()
may return an error then I noticed that the GetTime()
method has an error return parameter.
Is there any acceptable reason to has an error value in the return parameters? There is no returned error in the getTime()
method. Only returns nil value at the end of the method.
Title.
I input in terminal go get github.com/google/uuid
Go version: - go version go1.15.3 darwin/amd64
Go env
GO111MODULE=""
GOARCH="amd64"
GOBIN="/Users/vovs03/go/bin"
GOCACHE="/Users/vovs03/Library/Caches/go-build"
GOENV="/Users/vovs03/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/vovs03/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/vovs03/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/zr/05xnlj6d0bz4fqxf6mv7km1h0000gn/T/go-build085126828=/tmp/go-build -gno-record-gcc-switches -fno-common"
result of
go get github.com/google/uuid
How can me solve this problem? Any ideas...
We are passing 16 byte binary UUIDs via grpc and need to be able to cast these from byte slice back to type uuid.UUID. There doesn't seem to be an easy way to do this. It would be nice if the package had a method for this.
This works but is there a better way?
var b [16]byte
copy(b[:], bslice)
guid := uuid.UUID(b)
v1.3.0 introduced the EnableRandPool
and DisableRandPool
functions as a means of optimizing UUID generation at the expense of security. However, there are two main issues with this.
First, as documented, neither of these are thread-safe. However, the described solution is not feasible:
// Both EnableRandPool and DisableRandPool are not thread-safe and should
// only be called when there is no possibility that New or any other
// UUID Version 4 generation function will be called concurrently.
I cannot in general easily account for what all the package initializers of all of my transitive dependencies are doing. Instead of a function called a runtime, this opt-in behavior should be controlled by a build tag, so the pool can be enabled at compile time. Then there is no race condition. (You could also replace the poolEnabled
bool with an atomically read/written uint32, which at least resolves the race condition. But the build tag is more air tight.)
Second, as documented, the optimization is not suitable for security sensitive applications. However, again, I cannot account for what all of my transitive dependencies are doing. And in general, only having a global flag that effectively disables security seems like a rather poor design choice. It would be preferable if the decision could be made by the client on a case-by-case basis.
Going forward, it probably makes sense to deprecate the various global constructor functions and replace them with a factory object, similar to net.Dialer
. Then this factory can easily be configured with various options that accumulate over time without needing to make new constructor functions.
'from' is repeated twice in this comment:
https://godoc.org/github.com/google/uuid#NewRandom
A note about uniqueness derived from from the UUID Wikipedia entry:
NewRandom()
returns an error, not a panic:
https://godoc.org/github.com/google/uuid#NewRandom
NewRandom returns a Random (Version 4) UUID or panics.
It is surprising New()
panics when compared to the html/template
package, for example, where functions that panic include the word Must:
var t = template.Must(template.New("name").Parse("html"))
https://godoc.org/github.com/google/uuid#New
New
iscreates a new random UUID or panics. New is equivalent to the expression
I run a horizontally scaled application in k8s producing UUIDs for messages. However, rarely, some replicated pods restart due to a panic coming for the UUID library.
panic: unexpected EOF
goroutine 197286 [running]:
github.com/google/uuid.Must(...)
/home/vagrant/go/pkg/mod/github.com/google/[email protected]/uuid.go:178
github.com/google/uuid.New(...)
/home/vagrant/go/pkg/mod/github.com/google/[email protected]/version4.go:14
Is there any OS/library causing these issues, like too little entropy? On my local machine, I run a test producing billions of UUIDs without any panic.
I found this by using Go 1.11 modules. It would download the v1.0.0 zip file but the file contents are quite old. The copyright on each file is from 2016 and the MustParse
function is missing.
I manually download the zip and tar.gz files and they also contain the old source.
https://github.com/google/uuid/archive/v1.0.0.zip
https://github.com/google/uuid/archive/v1.0.0.tar.gz
I had to switch my go modules to use master to work around this issue.
Hello, we have a scenario that needs to generate UUID quickly.
At present, its performance in multi-threaded environment is not ideal. Do you have any solutions
Here is the benchmark data:
BenchmarkUUIDSinleGoroutine-32 1000000000 0.0000038 ns/op 0 B/op 0 allocs/op
BenchmarkUUIDMultiGoroutine-32 2307704 523.6 ns/op 16 B/op 1 allocs/op
Thanks :)
err is always nil, is there any reason behind it? I know it probably won't be fixed to avoid breaking changes. But doesn't this cause unneeded overhead, or is the compiler smart enough to ignore this?
// MarshalBinary implements encoding.BinaryMarshaler.
func (uuid UUID) MarshalBinary() ([]byte, error) {
return uuid[:], nil
}
Line 27 in 9b3b1e0
First, thank you for the work on this project.
The RFC Link in the README no longer takes you to the correct page. More of a heads up than anything :)
I would like to prepare and submit a pull request that adds parsing support for two string forms that are not RFC-4122 compliant:
Braced
{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
Non-dashed
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The first is commonly generated by APIs and tools on the Windows platform.
The second is the hexadecimal encoding of the uuid without any further treatment.
Both assume the hexadecimal values to be in big-endian order, as per the spec. Any platform-specific byte-reordering would be left to the user.
The form of an input string can quickly be determined by its length, and the lengths are unique so parsing remains deterministic.
My online app is use this lib by uuid.New(),
About 3 million concurrent
I found per call of uuid.New() cost more than 9 minutes.
I found many mutex in it's call chain.
Is there any problems?
Hi,
Thank you for the package! I'm struggling with the following problem due installation instruction from README. Right after the command go get github.com/google/uuid
I'm getting the following error:
$ go get github.com/google/uuid
go: downloading github.com/google/uuid v1.3.0
go get: github.com/google/[email protected]: verifying module: github.com/google/[email protected]: Get "https://sum.golang.org/lookup/github.com/google/[email protected]": x509: certificate signed by unknown authority
version:
$ go version
go version go1.17.2 darwin/amd64
Could you help me please?
In order to allow uuid.UUID
to work with the standard sql package to represent a UUID value that can be NULL in the database I suggest to implement a NullUUID
the same way as
it's done in http://github.com/satori/go.uuid [1]
[1] https://pkg.go.dev/github.com/satori/[email protected]?tab=doc#NullUUID
Greetings !!
How do I print the time of the parsed UUID?
Thanks in advance.
There appears to be named constants defined for Variant but not Version?
Just wondering approximately when 1.0 / stable API will come so we can use on production apps.
Thanks!
According to the UUID spec, the value is case sensitive. The ToString() function in UUID however lower cases everything. Is there a way to maintain case?
I can write a convenience function to check for the zero value. For example:
package main
import (
"fmt"
"github.com/google/uuid"
)
func IsZero(id uuid.UUID) bool {
for x := 0; x < 16; x++ {
if id[x] != 0 {
return false
}
}
return true
}
func main() {
id := uuid.UUID{}
fmt.Printf("is %v zero? %t\n", id, IsZero(id))
id, _ = uuid.NewRandom()
fmt.Printf("is %v zero? %t\n", id, IsZero(id))
}
Is that the thing to do, or is there a better way to check for the zero value?
Hey,
I installed uuid via glide init method, which recognizes the release as:
- package: github.com/google/uuid
version: ^0.1.0
This causes the following error during compile time:
./vendor/github.com/google/uuid/json.go:28: multiple-value Parse() in single-value context
Thanks,
Asaf.
Please comment in this issue about any requested API changes.
There is a typo in the latest tag v.1.1.2
. Must be v1.1.2
.
It would be nice if the uuid.Invalid
documentation or the (uuid.UUID).Variant()
documentation mentioned this in addition to the readme, as it was confusing until I saw 3943dc5. I had read through the documentation, code, and tests before the readme of the repository, so there was a little wasted effort and confusion.
Specifically, the unit tests are a little misleading, as uuid.Parse()
returns an error in the Invalid cases:
Lines 62 to 67 in 44b5fee
The variant is never checked in the unit tests in an error scenario:
Lines 99 to 101 in 44b5fee
Is it right that MarshalText()
function, if the input is not valid, returns the same output ([]byte("null")
) as MarshalJSON()
function?
Line 85 in 44b5fee
Wouldn't it be better if it returned a[]byte{}
?
Thank you, and sorry if my question seems stupid.
Hi, I am using this package to generate uuids for a test generator. I have a use case where multiple instances of the generator run asynchronously to create tests.
I need to be able to recreate failed tests, the current implementation holds only one seed, so there is no way to ensure recreation when processes are running asynchronously.
I have forked the repository and added a UuidSource
, similar to a source in math/rand, which holds the rander
, this solves my use case.
I suggest to do a PR from my fork.
Search for "uuid" under the "go" Topics, this item cannot be searched
I see NewUUID
internally call GetTime
which returns error
as a return value but this value will always be nil
(https://github.com/google/uuid/blob/master/time.go#L45-L67).
So, it doesn't make any sense to return error from NewUUID
when the value is always nil
.
Binary UUID format in SQL has much better performance than text UUID format in SQL. Could we get support for seamless binary UUID marshaling?
Hi! I noticed there is a uuid.Nil for UUID v1 but no uuid.Nil (for example uuid.Nil4) for UUID v4 could be useful adding this method to the library? (I could also make a PR)
Would it be possible/desirable to support parsing empty strings in JSON as uuid.Nil?
Currently it generates "invalid UUID length: 0": https://play.golang.org/p/K4y-DFj44Z6
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
k, _ := uuid.Parse("A string")
fmt.Println(k)
}
00000000-0000-0000-0000-000000000000
I'm getting the following test failures with Golang 1.10:
=== RUN TestNode
--- FAIL: TestNode (0.00s)
uuid_test.go:306: NodeInterface returned an empty string
=== RUN TestNodeID
--- FAIL: TestNodeID (0.00s)
uuid_test.go:376: NodeInterface "user" after SetInteface
It would be nice to have a reference implementation for UUID v8 as defined here:
https://www.ietf.org/id/draft-peabody-dispatch-new-uuid-format-03.html
Greetings!
I would like to know why version 1 repeats the ends of sequences, ie using NewUUID() the results always end in -0022684e5e1b. Is there a way to change this or a purpose for this to occur?
Thanks in advance.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.