Nano ID implementation in Go -- unique ID generator
GolangWebDev
GolangWebDev
954 0 0

Nano ID implementation in Go -- unique ID generator

go-nanoid is a Go implementation of nanoid

Features

Features of the nanoid spec are:

  • Use of hardware random generator
  • Uses a larger charset (A-Za-z0-9_-) than UUID
  • Faster than UUID
  • URL friendly

Features of this specific implementation are:

  • Fastest and most performant implementation of Nano ID
  • Prefetches random bytes in advance
  • Uses optimal memory
  • No production dependencies

Example

import (
	"log"
	"math/rand"
	"time"
	"github.com/jaevor/go-nanoid"
)

func main() {
  createNanoid, err := nanoid.Standard(21)
  if err != nil {
    panic(err)
  }

  id1 := createNanoid()
  log.Printf("ID 1: %s", id1) // p7aXQf7xK3jlfecYGKeRK

  // [!] Remember to seed. 
  rand.Seed(time.Now().Unix())

  createNonSecureNanoid, err := nanoid.StandardNonSecure(21)
  if err != nil {
    panic(err)
  }

  id2 := createNonSecureNanoid()
  log.Printf("ID 2: %s", id2) // japKZqwnQvllgUQ8lwgkP

  createCustomNanoid, err := nanoid.Custom("0123456789", 12)
  if err != nil {
    panic(err)
  }

  id3 := f3()
  log.Printf("ID 3: %s", id3) // 462855288020
}

Notes

Developed in Go 1.18.3

Remember to rand.Seed(...) before using the non-secure generators.

The generation of non-secure Nano IDs are not as fast as they could be yet

View go-nanoid at github.

0

See Also


Discussion

Login Topics