美文网首页go语言Go
GO语言 短URL生成

GO语言 短URL生成

作者: ljh123 | 来源:发表于2018-10-06 00:02 被阅读67次

    短URL介绍链接:
    1)https://segmentfault.com/a/1190000012088345
    2)http://www.voidcn.com/article/p-ydjqllgt-ed.html
    3)https://pathbox.github.io/2018/02/22/short-url-build-system/

    开始撸代码:

    package main
    
    import (
        "crypto/md5"
        "fmt"
        "strconv"
        "strings"
    )
    var chars = strings.Split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "")
    
    // 1) 哈希实现
    func hashShortUrl(url string) {
        hex := fmt.Sprintf("%x", md5.Sum([]byte(url)))
        resUrl := make([]string, 4)
        for i := 0;i < 4;i++ {
            val, _ := strconv.ParseInt(hex[i*8:i*8+8], 16, 0)
            lHexLong := val & 0x3fffffff
            outChars := ""
            for j := 0;j < 6;j++ {
                outChars += chars[0x0000003D & lHexLong]
                lHexLong >>= 5
            }
            resUrl[i] = outChars
        }
        fmt.Println(resUrl)
    }
    
    // 2) 自增长算法
    func autoShortUrl(id int64) string {
        return GetString62(Encode62(id))
    }
    
    func Encode62(id int64) []int64 {
        tempE := []int64{}
    
        for id > 0 {
            tempE = append(tempE, id % 62)
            id /= 62
        }
        return tempE
    }
    
    func GetString62(indexA []int64) string {
        res := ""
    
        for _, val := range indexA {
            res += chars[val]
        }
        return reverseString(res)
    }
    
    // 反转字符串
    func reverseString(s string) string {
        runes := []rune(s)
        for from, to := 0, len(runes) - 1;from < to;from, to = from + 1, to - 1 {
            runes[from], runes[to] = runes[to], runes[from]
        }
        return string(runes)
    }
    
    func main()  {
        fmt.Println(autoShortUrl(123))
    }
    

    相关文章

      网友评论

        本文标题:GO语言 短URL生成

        本文链接:https://www.haomeiwen.com/subject/wjlcaftx.html