snowflake

package module
v0.0.0-...-e18a122 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 18, 2025 License: BSD-2-Clause Imports: 3 Imported by: 0

README

Snowflake IDs Generator

godoc.org wiki

Go package to generate and parse unique IDs based on Twitter's Snowflake algorithm.

Getting Started

Installing

go get github.com/smnvdev/snowflake

Simple Usage

package main

import (
    "fmt"
    "github.com/smnvdev/snowflake"
)

func main() {
    machineID := 1
    g, err := snowflake.NewGenerator(machineID)
	if err != nil {
		fmt.Println(err)
		return
	}

    id := g.Next()
    fmt.Println(id)
}

Parse ID

You can parse the ID to get the timestamp, machine ID, and sequence number using the Parse function of the generator.

Custom Epoch

This package uses the Twitter Epoch of 1288834974657 or Nov 04 2010 01:42:54 by default. You can set your own epoch value by setting snowflake.SetEpochTime before creating a new generator.

Custom Machine ID

You can set your own machine ID by setting snowflake.SetMachineID before creating a new generator.

Custom Sequence Bits

You can set your own sequence bits by setting snowflake.SetSequenceBits before creating a new generator.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetEpochTime

func SetEpochTime(t time.Time)

func SetMachineIdBits

func SetMachineIdBits(bits int) error

func SetMachineSequenceBits

func SetMachineSequenceBits(bits int) error

Types

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

func NewGenerator

func NewGenerator(machineId int, opts ...Option) (g *Generator, err error)

func (*Generator) Next

func (g *Generator) Next() int64

func (*Generator) Parse

func (g *Generator) Parse(id int64) (timestamp time.Time, machineId, sequence int64)

type Option

type Option func(g *Generator)

func WithClock

func WithClock(t func() time.Time) Option

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL