Last active
January 29, 2022 20:45
-
-
Save knation/3541b4da1c5274eaf03ceafa6985bd0a to your computer and use it in GitHub Desktop.
Example of object ID management in Golang (uses ksuid)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Used to create, manage, and parse unique IDs. This code creates stripe-like IDs, | |
// (e.g., xx_000000000000000000000000000). It allows for a prefix and a 27 | |
// character ksuid separated by an underscore. The prefix makes it easy | |
// to visibly identify what the ID is for. | |
// | |
// Author: Kirk Morales | |
package util | |
import ( | |
"fmt" | |
"github.com/segmentio/ksuid" | |
) | |
// Number of characters before the underscore in an ID | |
const prefixLength = 2 | |
// Define enum for ID types | |
type ObjectId int32 | |
const ( | |
UndefinedId ObjectId = iota | |
DogId | |
CatId | |
) | |
// `idData` contains data for each ObjectId | |
var idData = map[ObjectId]([]string){ | |
UndefinedId: {"", "undefined"}, | |
DogId: {"do", "dog"}, | |
CatId: {"ca", "cat"}, | |
} | |
// Used as a reverse lookup of ObjectId by prefix | |
var prefixLookup map[string]ObjectId | |
var prefixLookupInit = false | |
// Populates `prefixLookup` | |
func createPrefixLookup() { | |
prefixLookup = make(map[string]ObjectId) | |
for key, val := range idData { | |
prefixLookup[val[0]] = key | |
} | |
} | |
// `String()` method for `ObjectType` | |
func (objectType ObjectId) String() string { | |
return idData[objectType][1] | |
} | |
// Creates an ID string for the given object type | |
func CreateId(objectType ObjectId) string { | |
if objectType == UndefinedId { | |
return "" | |
} | |
id := ksuid.New().String() | |
prefix := idData[objectType][0] | |
return fmt.Sprintf("%s_%s", prefix, id) | |
} | |
// Gets the object type for the given ID string | |
func GetIdType(id string) ObjectId { | |
if len(id) != (prefixLength+28) || id[prefixLength:prefixLength+1] != "_" { | |
return UndefinedId | |
} | |
if !prefixLookupInit { | |
createPrefixLookup() | |
prefixLookupInit = true | |
} | |
objType := prefixLookup[id[0:2]] | |
if objType != 0 { | |
return objType | |
} else { | |
return UndefinedId | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used to create, manage, and parse unique IDs. This code creates stripe-like IDs, (e.g.,
xx_000000000000000000000000000
). It allows for a prefix and a 27 character ksuid separated by an underscore. The prefix makes it easy to visibly identify what the ID is for.How to use
idData
to include the prefix and name of each ID typeExample