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.
go get github.com/indrasaputra/hashids
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}
For now, this package only support encoding to JSON, decoding from JSON, and encode as a string.