How do I create a URL shortener?

后端 未结 30 2658
我寻月下人不归
我寻月下人不归 2020-11-22 05:11

I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to \"http://www.example.org/abcdef\

30条回答
  •  佛祖请我去吃肉
    2020-11-22 05:35

    Very good answer, I have created a Golang implementation of the bjf:

    package bjf
    
    import (
        "math"
        "strings"
        "strconv"
    )
    
    const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    
    func Encode(num string) string {
        n, _ := strconv.ParseUint(num, 10, 64)
        t := make([]byte, 0)
    
        /* Special case */
        if n == 0 {
            return string(alphabet[0])
        }
    
        /* Map */
        for n > 0 {
            r := n % uint64(len(alphabet))
            t = append(t, alphabet[r])
            n = n / uint64(len(alphabet))
        }
    
        /* Reverse */
        for i, j := 0, len(t) - 1; i < j; i, j = i + 1, j - 1 {
            t[i], t[j] = t[j], t[i]
        }
    
        return string(t)
    }
    
    func Decode(token string) int {
        r := int(0)
        p := float64(len(token)) - 1
    
        for i := 0; i < len(token); i++ {
            r += strings.Index(alphabet, string(token[i])) * int(math.Pow(float64(len(alphabet)), p))
            p--
        }
    
        return r
    }
    

    Hosted at github: https://github.com/xor-gate/go-bjf

提交回复
热议问题