Skip to content

Instantly share code, notes, and snippets.

@ego008
Forked from eahydra/shorturl.go
Created June 28, 2017 09:32
Show Gist options
  • Save ego008/87a0743c079b2531e11952555aed9ec5 to your computer and use it in GitHub Desktop.
Save ego008/87a0743c079b2531e11952555aed9ec5 to your computer and use it in GitHub Desktop.
make a long url to short. It just allocate a ID for a URL, then convert the id to 62-base ID. Then format new id to string with kBase62CharMap.
package shorturl
import (
"math"
)
const kMinShortUrlLength = 6
var kBase62CharMap = []rune{
'0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
}
func convert_to_base62(id uint64) []byte {
var quotient uint64 = id
var remainder uint64
var r []byte
for quotient != 0 {
quotient, remainder = quotient/62, quotient%62
r = append(r, byte(remainder))
}
return r
}
func convert_from_base62(r string) uint64 {
var id uint64
var num_index uint64
for _, v := range r {
var i uint64
if v >= '0' && v <= '9' {
i = uint64(v - '0')
} else if v >= 'A' && v <= 'Z' {
i = uint64(v-'A') + 10
} else if v >= 'a' && v <= 'z' {
i = uint64(v-'a') + 36
}
id += i * uint64(math.Pow(float64(62), float64(num_index)))
num_index++
}
return id
}
func generateShortUrl(id uint64) string {
v := convert_to_base62(id)
if i := kMinShortUrlLength - len(v); i > 0 {
for j := 0; j < i; j++ {
v = append(v, byte(0))
}
}
var s []rune
for _, r := range v {
s = append(s, kBase62CharMap[r])
}
return string(s)
}
func Generate(url string, allocateId func(url string) (id uint64, err error)) string {
id, err := allocateId(url)
if err != nil {
return ""
}
s := generateShortUrl(id)
return s
}
func Query(short string, reserveQuery func(id uint64) (l string, err error)) string {
id := convert_from_base62(short)
s, err := reserveQuery(id)
if err != nil {
return ""
}
return s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment