nanoid: github.com/aidarkhanov/nanoid Index | Examples | Files

package nanoid

import "github.com/aidarkhanov/nanoid"

Package nanoid provides fast and convenient unique string ID generator.

Index

Examples

Package Files

nanoid.go

func Format Uses

func Format(random BytesGenerator, alphabet string, size int) (string, error)

Format generates a random string with the passed in bytes generator.

Code:

alphabet := "-0123456789ABCDEFGHIJKLNQRTUVWXYZ_cfgijkpqtvxz"
size := 21

// randomBytesGenerator returns random bytes buffer
// to pass it in Format function
randomBytesGenerator := func(step int) ([]byte, error) {
    buffer := make([]byte, step)
    if _, err := rand.Read(buffer); err != nil {
        return nil, err
    }
    return buffer, nil
}

id, err := nanoid.Format(randomBytesGenerator, alphabet, size)
if err != nil {
    panic(err)
}

fmt.Println(id)

func Generate Uses

func Generate(alphabet string, size int) (string, error)

Generate generates a random string.

Code:

alphabet := "-0123456789ABCDEFGHIJKLNQRTUVWXYZ_cfgijkpqtvxz"
size := 21

id, err := nanoid.Generate(alphabet, size)
if err != nil {
    panic(err)
}

fmt.Println(id)

func Must Uses

func Must(id string, err error) string

Must returns a random string if err is nil and panics otherwise.

func MustFormat Uses

func MustFormat(random BytesGenerator, alphabet string, size int) string

MustFormat is like Format but panics if a random string cannot be generated.

Code:

alphabet := "-0123456789ABCDEFGHIJKLNQRTUVWXYZ_cfgijkpqtvxz"
size := 21

// randomBytesGenerator returns random bytes buffer
// to pass it in Format function
randomBytesGenerator := func(step int) ([]byte, error) {
    buffer := make([]byte, step)
    if _, err := rand.Read(buffer); err != nil {
        return nil, err
    }
    return buffer, nil
}

id := nanoid.MustFormat(randomBytesGenerator, alphabet, size)

fmt.Println(id)

func MustGenerate Uses

func MustGenerate(alphabet string, size int) string

MustGenerate is like Generate but panics if a random string cannot be generated.

Code:

alphabet := "-0123456789ABCDEFGHIJKLNQRTUVWXYZ_cfgijkpqtvxz"
size := 21

id := nanoid.MustGenerate(alphabet, size)

fmt.Println(id)

func New Uses

func New() string

New generates a random string based on default alphabet and size.

Code:

id := nanoid.New()

fmt.Println(id)

type BytesGenerator Uses

type BytesGenerator func(step int) ([]byte, error)

BytesGenerator represents calculated random bytes buffer.

Package nanoid imports 3 packages (graph). Updated 2019-07-02. Refresh now. Tools for package owners.