Search code examples
gouuid

Generate uuid based on a namespace/string in Go


I would like to generate uuids based on a string value and also be able to check given a uuid, if it was generated using that string. I will use this in marking the uuids I use with my system's instance name. Is there a way to achieve that in Go?


Solution

  • There are different types of UUIDs (See Wikipedia although the list is not complete). Version 5 is the one that is generated based on user data.

    package main
    
    import (
        "fmt"
    
        "github.com/google/uuid"
    )
    
    func main() {
        fmt.Println(v5UUID("custom data"))
        fmt.Println(v5UUID("custom data"))
        fmt.Println(v5UUID("other data"))
    }
    
    func v5UUID(data string) uuid.UUID {
        return uuid.NewSHA1(uuid.NameSpaceURL, []byte(data))
    }
    

    Playground

    UUID version 5 is based on a namespace UUID. In the example above uuid.NameSpaceURL is used. It is a well known namespace UUID. You can replace it with your own static UUID or uuid.Nil.

    Given the same data is available at verification time, the same UUID can be generated again and compared.

    Caveat: Since the same data will lead to the same UUID, the data must be unique or the UUID will not be unique. Different namespace UUIDs can be used for different domains where uniqueness is given.


    Edit based on comment below:

    None of the UUID formats that exist can accommodate for those requirements.

    The only one that could is the new Version 8. That is a custom format for custom based implementations.

    Downside: you are on your own. You have 122 bits you can set however you like. At the same time collisions are your own problem / risk.

    The Go uuid library mentioned above can create a uuid from any 16 byte long []byte with uuid.FromBytes.