token

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2020 License: MIT Imports: 4 Imported by: 1

README

Use v2 Instead

Warning: Breaking Changes

Version 2 of this package is ready for production use. You can find it here.

The order of the Base62 characters have been changed in v2 so that the string representation of the Token and the int representation of the token are in the same sort order. This is useful when scaling your app or using NoSQL solutions. Special thanks to @sudhirj for the suggestion.

References

https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c

https://developer.twitter.com/en/docs/basics/twitter-ids.html

https://github.com/ulid/spec


GoDoc

This is a simple package for go that generates randomized base62 encoded tokens based on an integer. It's ideal for short url services or for any short, unique, randomized tokens you need to use throughout your app.

How it Works

Token is an alias for uint64.

The Token.Encode() method returns a base62 encoded string based off of the uint64.

Token implements the encoding.TextMarshaler and encoding.TextUnmarshaler interfaces to encode and decode to and from the base62 string representation of the uint64

Basically, the outside world will always see the token as a base62 encoded string, but in your app you will always be able to use the token as a uint64 for fast, indexed, unique, lookups in various databases.

IMPORTANT: Remember to always check for collisions when adding randomized tokens to a database

Example

package main

import (
	"fmt"
	"github.com/marksalpeter/token"
)

type Model struct {
    ID	token.Token `json:"id"`
}

func main() {
	// create a new model
	model := Model {
		ID:	token.New(), // creates a new, random uint64 token
	}
	fmt.Println(model.ID)          // 2751173559858
	fmt.Println(model.ID.Encode()) // Mr1NSSu

	// encode the model as json
	marshaled, err := json.Marshal(&model)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(marshaled)) // {"id":"Mr1NSSu"}

	// decode the model
	var unmarshaled Model
	if err := json.Unmarshal(marshaled, &unmarshaled); err != nil {
		panic(err)
	}
	fmt.Println(unmarshaled.ID)    // 2751173559858

}

Special Mentions

Special thanks to @einsteinx2. The encode and decode functions are ported from a short url project of his and he graciously allowed me to publish them.

Documentation

Index

Examples

Constants

View Source
const (
	// ErrTokenTooSmall is the error returned or panic'd when a base62 token is smaller than `MinTokenLength`
	ErrTokenTooSmall = Error("the base62 token is smaller than MinTokenLength")

	// ErrTokenTooBig is the error returned or panic'd when a base62 token is larger than `MaxTokenLength`
	ErrTokenTooBig = Error("the base62 token is larger than MaxTokenLength")

	// ErrInvalidCharacter is the error returned or panic'd when a non `Base62` string is being parsed
	ErrInvalidCharacter = Error("there was a non base62 character in the token")
)
View Source
const (
	// Base62 is a string respresentation of every possible base62 character
	Base62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	// MaxTokenLength is the largest possible character length of a token
	MaxTokenLength = 10

	// MinTokenLength is the smallest possible character length of a token
	MinTokenLength = 1

	// DefaultTokenLength is the default size of a token
	DefaultTokenLength = 9
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

type Error string

Error is a token error

func (Error) Error

func (e Error) Error() string

Error implements the `errors.Error` interface

type Token

type Token uint64

Token is an alias of an uint64 that is marshalled into a base62 encoded token

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/marksalpeter/token"
)

type Model struct {
	ID token.Token
}

func main() {

	model := Model{
		ID: token.New(),
	}
	var unmarshaled Model
	marshaled, _ := json.Marshal(&model)
	json.Unmarshal(marshaled, &unmarshaled)

	fmt.Println(model.ID)
	fmt.Println(model.ID.Encode())
	fmt.Println(string(marshaled))
	fmt.Println(uint64(unmarshaled.ID))

}
Output:

2751173559858
Mr1NSSu
{"ID":"Mr1NSSu"}
2751173559858

func Decode

func Decode(token string) (Token, error)

Decode returns a token from a 1-12 character base62 encoded string

func New

func New(tokenLength ...int) Token

New returns a `Base62` encoded `Token` of *up to* `DefaultTokenLength` if you pass in a `tokenLength` between `MinTokenLength` and `MaxTokenLength` this will return a `Token` of *up to* that length instead if you pass in a `tokenLength` that is out of range it will panic

func (Token) Encode

func (t Token) Encode() string

Encode encodes the token into a base62 string

func (Token) MarshalText

func (t Token) MarshalText() ([]byte, error)

MarshalText implements the `encoding.TextMarsheler` interface

func (*Token) UnmarshalText

func (t *Token) UnmarshalText(data []byte) error

UnmarshalText implements the `encoding.TextUnmarshaler` interface

Jump to

Keyboard shortcuts

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