38 lines
735 B
Go
38 lines
735 B
Go
package shorturl
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"math/big"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
|
|
// Takes UUID string and returns 12-char slug
|
|
func SlugFromUUID(uuid uuid.UUID) string {
|
|
sum := sha256.Sum256([]byte(uuid.String()))
|
|
|
|
// 9 bytes = 72 bits → enough for 12 base62 chars
|
|
return base62Fixed(sum[:9], 12)
|
|
}
|
|
|
|
func base62Fixed(data []byte, length int) string {
|
|
n := new(big.Int).SetBytes(data)
|
|
base := big.NewInt(62)
|
|
mod := new(big.Int)
|
|
|
|
out := make([]byte, length)
|
|
|
|
for i := length - 1; i >= 0; i-- {
|
|
if n.Sign() == 0 {
|
|
out[i] = alphabet[0]
|
|
continue
|
|
}
|
|
n.DivMod(n, base, mod)
|
|
out[i] = alphabet[mod.Int64()]
|
|
}
|
|
|
|
return string(out)
|
|
}
|