GithubHelp home page GithubHelp logo

go.uuid's Introduction

UUID package for Go language

Build Status Coverage Status GoDoc

This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs.

With 100% test coverage and benchmarks out of box.

Supported versions:

  • Version 1, based on timestamp and MAC address (RFC 4122)
  • Version 2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1)
  • Version 3, based on MD5 hashing (RFC 4122)
  • Version 4, based on random numbers (RFC 4122)
  • Version 5, based on SHA-1 hashing (RFC 4122)

Installation

Use the go command:

$ go get github.com/satori/go.uuid

Requirements

UUID package tested against Go >= 1.6.

Example

package main

import (
	"fmt"
	"github.com/satori/go.uuid"
)

func main() {
	// Creating UUID Version 4
	// panic on error
	u1 := uuid.Must(uuid.NewV4())
	fmt.Printf("UUIDv4: %s\n", u1)

	// or error handling
	u2, err := uuid.NewV4()
	if err != nil {
		fmt.Printf("Something went wrong: %s", err)
		return
	}
	fmt.Printf("UUIDv4: %s\n", u2)

	// Parsing UUID from string input
	u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	if err != nil {
		fmt.Printf("Something went wrong: %s", err)
		return
	}
	fmt.Printf("Successfully parsed: %s", u2)
}

Documentation

Documentation is hosted at GoDoc project.

Links

Copyright

Copyright (C) 2013-2018 by Maxim Bublis [email protected].

UUID package released under MIT License. See LICENSE for details.

go.uuid's People

Contributors

alindeman avatar artnez avatar cbandy avatar daskol avatar dlsniper avatar epels avatar haraldnordgren avatar jrouviere avatar kevinburke avatar marclave avatar mjolnir42 avatar satori avatar sckelemen avatar tomstokes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go.uuid's Issues

Is uuid.NewV4() thread safe?

When I call uuid.NewV4() in multiple goroutine, I have some question:

  • thread-safe?
  • Can I get same uuid when multiple goroutine call it at same time?
    P/s: sorry for my bad English

Thanks.

NewV4: non-random uuid

I'm running this on my macbook pro.

I'm using uuid.Must(uuid.NewV4()).String() to generate random identifiers. I'm generating theses identifiers at a very low rate of a few dozen per days

Here are some non-random UUID that I got in the last weeks:

02524e6f-65a7-4cf5-8000-0000000000002
6e3ef1c8-0000-4000-8000-0000000000001
fa07f1e9-a8a0-427f-8103-e34e000000000
2cfa392b-71d5-4000-8000-000000000000
5f16db16-56ce-4000-8000-000000000000
bac73b37-aab3-498b-8000-000000000000
da5bd82d-4f98-4b51-8000-000000000000
eb245e52-535f-4274-8350-3a7200000000
f7510000-0000-4000-8000-000000000000
5936f955-286e-47ac-8000-000000000000
0a14da92-0000-4000-8000-000000000000
80730000-0000-4000-8000-000000000000
cd2b88a5-0000-4000-8000-000000000000

I think I shouldn't have theses.

[Question] It doesn't support to transform between Big-endian and Little-endian in net work

Hi

I meet a problem when I use this code to query from Sql Server.

I define a "UNIQUEIDENTIFIER" column in database, i use "id uuid.UUID" to query from database.

The right value in DB is "C74037D4-D0BA-471C-9200-31187972F117".

But what i got is "d43740c7-bad0-1c47-9200-31187972f117", it seemed that front third has wrong sequence.

I see UUID define is "type UUID [Size]byte", it seems that it don't care network sequence.

I use this package "database/sql" to query DB which will process UUID as []byte.

It seemed that there will be a problem when UUID used in network.

Best regards
Forston

uuid: cannot convert uuid.UUID to UUID

I have the following struct

type Identity struct {
	gormsupport.Lifecycle
	// Link to User
	UserID uuid.NullUUID `sql:"type:uuid"`
	User   User
}

and

identity := account.Identity{
		User:         user,
		UserID:       uuid.NullUUID{UUID: uuid.NewV4(), Valid: true},
	}
err := s.identityRepo.Create(context.Background(), &identity)

and this is the Create method being called

// Create creates a new record.
func (m *GormIdentityRepository) Create(ctx context.Context, model *Identity) error {
	defer goa.MeasureSince([]string{"goa", "db", "identity", "create"}, time.Now())
	if model.ID == uuid.Nil {
		model.ID = uuid.NewV4()
	}
	err := m.db.Create(model).Error
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"identity_id": model.ID,
			"err":         err,
		}, "unable to create the identity")
		return errs.WithStack(err)
	}

The line m.db.Create(model).Error is failing with cannot convert uuid.UUID to UUID

Release new version?

Is there any way a 1.2.0 could be released with all the commits since 1.1.0? :)

uuid.FromString("6ba7b8109dad11d180b400c04fd430c8") does not work, and really should.

I feel the tests have an error in them, in that a format is not supported that really, really should be.

While uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8") is clearly supported, the string uuid.FromString(""6ba7b8109dad11d180b400c04fd430c8") should also work as well as its considered a valid uuid in many languages and schema frameworks and so this support is important for interoperability... just it does not work at the moment even though it really should, and this has caused us (and I'm sure, many many others) all kinds of issues.

For example, this lack of support for UUID's without dashes makes dealing with marshmallow and Python generated .hex UUID values a big PITA when you trying to use the hex value as a primary key in a DB or massively distributed system.

It also means that while other libraries and languages are generating these "valid UUID's", the UUID framework itself does not support them, so it makes it look like this library doesn't have full support for UUID's.

I understand that some may want to create an overly pedantic discussion about if a UUID without a dash is really a UUID that won't take into account the fact real people are using these libraries to get work done and so this support would make lives easier, but the fact is most people consider them to be valid, many other frameworks consider them to be valid, and so this support really should exist if the core golang philosophy of getting stuff done is to be respected.

Implement json.Marshaler/Unmarshaler

I'd be useful and easy to implement the json.Marshaler/Unmarshaler interfaces just like the binary.BinaryMarshaler/BinaryUnmarshaler interfaces are.

I'll submit a PR if this sounds reasonable.

Helper function: Must

Some UUIDs are usually hardcoded rather than obtained / parsed from external sources. These UUIDs are probably best defined as "constants" (or rather, global don't-touch-this variables) and rather getting a nil UUID (i.e., FromStringOrNil), it's usually preferred to panic when the string is not a valid UUID. It will be nice if we can have Must function which is idiomatic in Go.

var packageUUID = uuid.Must(uuid.FromString("123e4567-e89b-12d3-a456-426655440000"));

sql.Scan does not work for mssql driver

Hi,

i am having a problem when scanning from MS SQL Server a uuid.
The uuid from the app and the value in the db table is the same, but when querying and scan the result i get a different uuid. The same app does work in PostgreSQL just by switching out the driver.
Any thoughts?

Can't scan into *uuid.UUID

Wondering if it's possible to support scanning into *uuid.UUID. Something like this:

type Team struct {
   ID *uuid.UUID
}

// ...
var team Team
err := row.Scan(&team.ID)

Right now it'll error out with:

can't scan into dest[0]: Scan cannot decode into *uuid.UUID

If I use uuid.NullUUID it does work, but I prefer using pointers in this context.

Get time from a UUID

Hello just a question
There is a way, and do this library provide a method to obtain the time from a UUID?
Thanks a lot

not enough arguments in call to uuid.Must

not enough arguments in call to uuid.Must
have (uuid.UUID)
want (uuid.UUID, error)

if I install the package using dep dep ensure -add github.com/satori/go.uuid, then Must function expects two arguments.

uuid := uuid.Must(uuid.NewV4(), errors.New("UUID Error"))

but if I install the package using go get github.com/satori/go.uuid, then Must function expects only 1 argument

uuid := uuid.Must(uuid.NewV4())

In both the cases 1.2 version is getting installed

Everything is broken

After this sudden change, everything in my code will NOT work. Not even build with docker

All I get is this multiple-value uuid.NewV4() in single-value context

Help reading UUID generated from java (Mongo driver)

Hi,

My java (Scala actually) app stores UUID values in mongodb.
If you look using the mongo client, the data looks like:

"_id" : BinData(3,"q0Q+Fc31LFsf1mLP6zWjgQ==")

if using go I call

uuid.FromBytes() and I pass the []byte I got from mongodb, I get
ab443e15-cdf5-2c5b-1fd6-62cfeb35a381
but I wa supposed to get
5b2cf5cd-153e-44ab-81a3-35ebcf62d61f

What I really need is to pass 5b2cf5cd-153e-44ab-81a3-35ebcf62d61f to your library and get back a []byte that I can use to search in mongo to find the correct document.

but calling uuid.FromString(cookie.Value) doesn't seem to do what I need.

Any help would be great!

Thanks

Invalid version error

I have a set of uuid's which were generated from different platforms and are very old, are now breaking after the recent commits 90e7075.

One such Id which I am using is : ba60a9fc-b22c-9d4c-970e-5fb8eacdbe16
I get "invalid version" when used with FromString.

Add IsZero method

Hi,

What do you think about adding IsZero method to UUID type? This is needed for go-pg to check if uuid does not have any value and generate

INSERT INTO table (uuid) VALUES (DEFAULT)

instead of

INSERT INTO table (uuid) VALUES ('00000000-0000-0000-0000-000000000000')

I already do this for time.Time and it works well. I can send PR if you don't mind.

New Version

Any plans on releasing a new version of this? Seems like a relatively large number of changes since the 1/10/18 release (1.2.0)

Consider archiving this repo

This repo is widely popular, but has a 4 month old critical defect #73, and uses tagging practices that incentivize people to unsafely include master in their projects. This is dangerous for the go ecosystem as a whole.

Please archive this repo if there is no intention to maintain it further.

Origin validation

This my seem odd feature request, but I was wandering about a use case that might be interesting to discuss.

Let's assume I have 100 devices with their own MAC addresses and let's assume that these devices generates their own UUIDs as part of the whole data.

At some point in time those devices send a request to the mother ship (cloud) with the newly generated UUIDs. For example, let's assume that each of those devices generate a small, sub graph, where those UUIDs are important part of the data inside.

Now, when you want to merge the data on the mother ship you'll have to validate that those UUIDs are really generated correctly, by using their own MAC addresses. A possible con might be one device to pretend to be another. Also, if you use timestamp as part of the UUID, you might want to verify that the UUID is generated by using a timestamp (or time interval between X and Y).

Since the package generates the UUIDs it would be a good question is it possible to be performed a symmetric check that validates the UUID by MAC and/or timestamp?

In my example, if I find on the cloud that the UUIDs are not generated with correct MAC or timestamp, I might decide to regenerate the UUIDs to assure data consistency. To generate one on the cloud I have to pass MAC and/or timestamp.

In this particular case I guess there will be needed a change in the constructors to accept MAC and timestamp as arguments (instead of unconditionally search for a network interface with setup MAC address and/or use current timestamp).

New Release possible?

The current release is nearly a year old. Is it possible to publish a new release?

Newer release

Since the latest tag / github release - the signatures of NewV1 / V2/ V4 has changed to return an error.

Can we have a github release so it is easier to integrate in dep that way ?

Is uuid.NewV4() globally unqiue?

If I use this package in 2 different packages and use these in my go command, will all uuids be unique?
Maybe it sounds like language specific question, I'm still new in Go.

json marshaling

with UUID, marshalling to json looks like {id: "f4ee338d-d66d-452f-93d5-440fa3ae980b"}, however a NullUUID looks like id: { UUID: "3bdef553-9b6a-4620-8a5f-b94bf22a2520", Valid: true },.

Is that your intent? If not I have a pull request that brings NullUUID in line with UUID by implementing encoding.TextMarshaller. Thanks.

Issue using go.uuid in docker container

This line: aggregateID, _ := uuid.NewV4() works perfectly when building on my machine, but I receive the error ./main.go:51:17: assignment mismatch: 2 variables but 1 values when building with the following docker image:

FROM golang:latest as builder
WORKDIR /go/src/github.com/zachlefevre/project_hopper_backend/algorithmAPI
COPY . .
RUN go get -u github.com/golang/dep/cmd/dep
RUN dep init && dep ensure

Any help would be greatly appreciated.

Allow to get UUIDs with random MAC address

In the current version using NewV1() and NewV2() the MAC address is only randomised when the network card is not found.

I would like to have a way to always have a random MAC address.

This is for security reason, as we don't want to expose it.

assignment mismatch: 2 variables but uuid.NewV4 returns 1 values

Hello everyone, I started experimenting with mod. When I initialize the modules in my project, all libraries are loaded and github.com/satori/go.uuid is loaded accordingly.. But when starting go run server.go, I get an error {
"resource": "/d:/myProject/oauth/tokenstore/tokenstore.go",
"owner": "generated_diagnostic_collection_name#0",
"severity": 8,
"message": "cannot initialize 2 variables with 1 values",
"source": "LSP",
"startLineNumber": 41,
"startColumn": 20,
"endLineNumber": 41,
"endColumn": 30
}

image

I am using vscode.

My project is outside gopath

API should return entropy errors

There is an issue with current library API, which doesn't allow library users to gracefully handle entropy errors. This problem was on my mind for some time, but looks like other people have concerns about it as well:

By the time safeRandom() has been introduced in #12, v1/v2 storage initialisation had been done inside init function, so it looked quite reasonable to panic there as it was the only way to handle errors during init.
But nothing is eternal and #13 moved v1/v2 storage initialisation out of init to make v3/v5 UUID generation possible without any entropy.

Although entropy failure occurs only in some rare and exotic cases, there is no really good reason to hide error or panic in library internals.
In the same time library became surprisingly popular across the community and it is not the best decision to suddenly break the current API without giving a time to adopt a new one.

So I would like to introduce a deprecation policy for current library API.

Unfortunately Go doesn't have a function overloading, and smooth deprecation of an old function signature leads to a new function name.

New API methods which would return (UUID, error) will be added and for next 6-12 months old API methods will emit the following warning messages via log.Printf:

uuid: uuid.NewV1() has been deprecated, use uuid.V1() instead.
uuid: See https://github.com/satori/go.uuid/issues/18 for more info.

After a reasonable amount of time (like 6-12 months, mentioned above), I will remove old API methods.

Thanks @m0sth8 for pointing me on that issue and suggesting a deprecation policy.

error value when doing rand.Read(...)

First of all thanks for a great library.

This is more of a question rather than a real issue: what happens if rand.Read() fails? I realize in practice it probably doesn't fail much (and I've been running a script locally to try and catch a random failure for crypt.Rand() but haven't had any luck) -- but in that rare case what should be the behavior of the library?

Maybe a retry works? If so I'll be happy to do a PR.

Truncated UUIDs in BINARY(16)

When using go-sql-driver's mysql package, occasionally (~1%-3% of the time), the uuid's get clipped when saving to the database. I haven't found a full pattern yet, so I can't be sure it's in your package, go-sql-driver's package, or something else. Here's what I know:

Git hash: b061729
MariaDB v10.1.16 on Windows 7x64 (also on Ubuntu 16.04 LTS)
Go 1.8
ID columns are BINARY(16)
UUIDv1
It sometimes truncates two characters, seemingly in the first eight characters (in the xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx form)
The last two characters become 00

Sample code:

import (
	"database/sql"
	"fmt"

	"github.com/satori/go.uuid"
)

func foo(db *sql.DB) {
	id := uuid.NewV1()
	_, _ := db.Exec(fmt.Sprintf("INSERT INTO bar (id, baz) VALUES ('%s', '%s')", id.Bytes(), "baq"))
}

In place of fmt.Sprintf, I have a parameter sanitizer.

Add deprecation notice in favor of github.com/gofrs/uuid and archive this repo

This is an issue to request that a deprecation notice be added to the README that points users to the fork created by some of us in the community (The Gofrs). In addition to that, it'd be good to mark the repo as being "archived" in the GitHub settings so that users get a nice warning that it's no longer maintained.

We plan to keep our fork maintained, as well as to include some of the feature requests / PRs on this repo.

This being done would, in some way, fix #73, #76, #80, #82, and #83.
This new repo also contains something similar to #75, and will hopefully include iterations of #44 and #50.

undefined: uuid.Must

Hi,

I am struggelig with dep and a dependency with this library. Unfortunately it seems like renstrom/shortuuid uses uuid.Must. Is it possible to get a release with this included so Dep can be satisfied ?

NilUUID/Nil instead of NullUUID

This would add consistency with the Go language AND the RFC 4122 specification. You can see here it's called a "Nil UUID" @ 4.1.7.

I think it would make more sense to at least have it as uuid.NilUUID, but probably the most sense as uuid.Nil since uuid.NilUUID is kind-of redundant since you always have the package name anyway.

Panic in UnmarshalText() when input has a certain form.

UnmarshalText() panics when input is exactly 32 bytes long and of the form

xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx

Example program:

package main

import (
        "github.com/satori/go.uuid"
        "fmt"
)

func main() {
        s36 := "7f31b5e7-83ee-404e-a278-f2cd3220aaaa"
        s35 := "7f31b5e7-83ee-404e-a278-f2cd3220aaa"
        s34 := "7f31b5e7-83ee-404e-a278-f2cd3220aa"
        s33 := "7f31b5e7-83ee-404e-a278-f2cd3220a"
        s32 := "7f31b5e7-83ee-404e-a278-f2cd3220"

        fmt.Println(uuid.FromString(s36))
        fmt.Println(uuid.FromString(s35))
        fmt.Println(uuid.FromString(s34))
        fmt.Println(uuid.FromString(s33))
        fmt.Println(uuid.FromString(s32)) // will panic
}

Output:

uuidcrash$ ./uuidcrash 
7f31b5e7-83ee-404e-a278-f2cd3220aaaa <nil>
7f31b5e7-83ee-404e-a278-f2cd3220aa00 encoding/hex: invalid byte: U+0000
7f31b5e7-83ee-404e-a278-f2cd3220aa00 encoding/hex: invalid byte: U+0000
7f31b5e7-83ee-404e-a278-f2cd32200000 encoding/hex: invalid byte: U+0000
panic: runtime error: slice bounds out of range

goroutine 1 [running]:
panic(0x5310c0, 0xc82000a0f0)
        /home/acln/go/src/runtime/panic.go:464 +0x3e6
github.com/satori/go%2euuid.(*UUID).UnmarshalText(0xc820047db0, 0xc82000e2d3, 0x8, 0x8, 0x0, 0x0)
        /home/acln/w/go/src/github.com/satori/go.uuid/uuid.go:247 +0x481
github.com/satori/go%2euuid.FromString(0x583520, 0x20, 0x4e40ee83e7b5317f, 0x78a2, 0x0, 0x0)
        /home/acln/w/go/src/github.com/satori/go.uuid/uuid.go:321 +0x97
main.main()
        /home/acln/w/go/src/github.com/andreicalin/uuidcrash/main.go:19 +0x6ba

I've investigated the cause of the panic.

In UnmarshalText(), when len(text) > 32 && len(text) < 36, cap(text) == 48. Therefore, in the final call to hex.Decode(), the access text[:byteGroup] does not panic, even if byteGroup > len(text), because byteGroup < cap(text).

However, when len(text) == 32, cap(text) == 32. In this case, accessing text[:byteGroup] with byteGroup > len(text) causes the panic.

Breaking API Change

0ef6afb breaks the API that's been stable for years. Why is this important enough to change with no warning, despite the community standard to be avoiding breaking API changes without some kind of versioning system? The original issue indicates some sort of deprecation warning was considered, but seems to never have been implemented. If users are going to have to rug pulled out from under them with no warning, why should we use this library?

is a uuid strip function help?

Hi, thanks for the great repo, but when I was using the repo, I found that sometimes I need a strip uuid, like 6ba7b8109dad11d180b400c04fd430c8, just get rid of - in line.

I have to use the strings package to replace the -, I was thinking if go.uuid can provided a strip function to make it simple

also, I can write a PR for this, if go.uuid like this proposal.

thanks

It has any sense NullUUID struct?

I don't found the explication to NullUUID struct. A array can't be nil, so a NULL value in databases should be a zero value in a array for Go.

I would change the Value method to:

func (u UUID) Value() (driver.Value, error) {
    if u.IsZero() {
         return nil, nil
    }
    return u.String(), nil
}

And would remove the NullUUID

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.