Currently, most scenarios use long connections, which have led to the creation of short links for various purposes (such as character limits on SMS platforms).
Short Link Generation#
- Generated through hash algorithms
- Generated through a number generator
Both can ultimately reduce length using base algorithms.
Hash Algorithm Generation#
Possible hash collisions
// 1.hash
func GenerateShortenUrl(initUrl, userID string) string {
// Encrypted with 256
urlSHA256 := sha256f(initUrl + userID)
genNum := new(big.Int).SetBytes(urlSHA256).Uint64()
// Base 58 excludes misleading letters o, O, I, l and +, /
// Reduces character length
return base58Encoded([]byte(fmt.Sprintf("%d", genNum)))[0:8]
}
func sha256f(input string) []byte {
hashed := sha256.Sum256([]byte(input))
return hashed[:]
}
func base58Encoded(input []byte) string {
encoded, err := base58.BitcoinEncoding.Encode(input)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
return string(encoded)
}
Number Generator Generation#
Generated ID using the Snowflake algorithm.
Redirection#
Generally redirected using
302
, while301
permanent redirection leaves a cache in the browser, making it impossible to gather statistics through short link access.