YouTube like ID offer a concise and unguessable way to reference content. In this post, we’ll explore how to generate YouTube like ID in Golang using the HashIds package. HashIds is a small open-source library that can create short, unique, non-sequential ids from numbers, which is perfect for our use case.
Table of Contents
Prerequisites
Before diving into generating IDs with the HashIds package, ensure you have a working environment with Go installed on your system. Knowledge of Go basics is beneficial for following the examples smoothly.
Installation of HashIds
To start using HashIds in your Go project, you need to install the package using the Go package manager. Run the following command in your terminal to install it:
go get github.com/speps/go-hashids
Generating Short ID with HashIds
HashIds require an initialization with or without a custom “salt” string that allows your IDs to be unique and hard to guess. The primary purpose is to encode integers into a short string which can be decoded back into the original integers.
Examples
Let’s illustrate the usage of HashIds with several examples to generate YouTube-like IDs.
Basic Example
The following function demonstrates generating a short ID without a custom salt:
package main
import (
"fmt"
"github.com/speps/go-hashids"
)
func generateShortID(number int64) string {
hd := hashids.NewData() // Initialize with default settings
h, _ := hashids.NewWithData(hd)
e, _ := h.EncodeInt64([]int64{number})
return e
}
func main() {
fmt.Println("Short ID:", generateShortID(123456789))
}
Output:
Short ID: PdzxpO
Using a Custom Salt
To make your IDs unique to your application, you can use a custom salt:
func generateShortIDWithSalt(number int64, salt string) string {
hd := hashids.NewData()
hd.Salt = salt
h, _ := hashids.NewWithData(hd)
e, _ := h.EncodeInt64([]int64{number})
return e
}
func main() {
fmt.Println("Short ID with custom salt:", generateShortIDWithSalt(123456789, "my custom salt"))
}
Output:
Short ID with custom salt: l9u8nV
Generating Shorter IDs
If you want to generate shorter IDs, you can adjust the minimum length of the HashID as follows:
func generateShortIDWithMinLength(number int64, minLength int) string {
hd := hashids.NewData()
hd.MinLength = minLength
h, _ := hashids.NewWithData(hd)
e, _ := h.EncodeInt64([]int64{number})
return e
}
func main() {
fmt.Println("Shorter Short ID:", generateShortIDWithMinLength(123456789, 5))
}
Output:
Shorter Short ID: VolejRejNm
Conclusion
We’ve looked at the HashIds package to Generate YouTube-like IDs in Golang, providing an effective way to generate short, unique, non-sequential IDs. We’ve seen how to install the package, use it with default settings, apply a custom salt, and control the length of the generated IDs. Play around with the package to fit it to your specific needs and enjoy the simplicity and elegance it brings to ID generation in your Golang applications.
References