Skip to content

Golang ID to Hash converter using Hashids algorithm.

License

Notifications You must be signed in to change notification settings

indrasaputra/hashids

Repository files navigation

Hashids

Go Report Card Workflow codecov Maintainability Quality Gate Status Go Reference

Hashids is a package to convert ID into a random string to obfuscate the real ID from user. In the implementation itself, the ID will still be an integer. But, when it is shown to the user, it becomes a random string. The generated random string can be decoded back to the original ID. This project uses https://github.com/speps/go-hashids as the backend.

Installation

go get github.com/indrasaputra/hashids

Example

Let there be a struct:

type Product struct {
    ID      hashids.ID  `json:"id"`
    Name    string      `json:"name"`
}

Then we have an instance of Product like this:

product := &Product{
    ID: hashids.ID(66),
    Name: "Product's name",
}

When the product is marshalled into a JSON, the ID will not be a plain integer. It will become a random string like this:

{
    "id": "kmzwa8awaa",
    "name": "product's name"
}

Upon decoding the ID, Hashids will decode back the random string to the original ID.

var product Product
b := []byte(`{"id": "kmzwa8awaa","name": "product's name"}`)
json.Unmarshal(b, &product)

The code above will fill the product's attributes like this:

{66 product's name}

Limitation

For now, this package only support encoding to JSON, decoding from JSON, and encode as a string.