Defining the Base62 algorithm

We saw how the Base62 algorithm works in the previous chapters. Here is the solid implementation of that algorithm. The logic is purely mathematical and can be found everywhere on the web. Take a look at the following code:

package base62 import ( "math" "strings" ) const base = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const b = 62 // Function encodes the given database ID to a base62 string func ToBase62(num int) string{ r := num % b res := string(base[r]) div := num / b q := int(math.Floor(float64(div))) for q != 0 { r = q % b temp := q / b q = int(math.Floor(float64(temp))) res = string(base[int(r)]) + res } return string(res) } // Function decodes a given base62 string to datbase ID ...

Get Building RESTful Web services with Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.