Skip to content

Instantly share code, notes, and snippets.

@knation
Last active January 29, 2022 20:45
Show Gist options
  • Save knation/3541b4da1c5274eaf03ceafa6985bd0a to your computer and use it in GitHub Desktop.
Save knation/3541b4da1c5274eaf03ceafa6985bd0a to your computer and use it in GitHub Desktop.
Example of object ID management in Golang (uses ksuid)
// 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
}
}
@knation
Copy link
Author

knation commented Dec 16, 2021

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

  1. Add the appropriate types to the ObjectId enum
  2. Update idData to include the prefix and name of each ID type

Example

// Create new unique ID
id := CreateId(DogId)
// "do_000000000000000000000000000"

// Get the type of an ID
idType := GetIdType(id)
// DogId

// Get the string name of an ID type
DogId.String()
// "dog"

// Bad ID
idType := GetIdType("bad_id")
// UndefinedId

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment