短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))
}

本站以现代、古代情诗为主,情诗网创办于2013年,以原创爱情诗歌、经典情诗、现代情诗、古代情诗、英文情诗、情诗绝句为主并收集古诗、古诗词、诗歌大全、诗词名句的文学门户。方便您下次继续阅读;可以放在浏览器的收藏夹中(快捷键Ctrl+D);或者看到喜欢或者有趣的诗词可以通过分享按钮给你的好友分享;情诗网是目前最全情诗大全网站之一。并欢迎广大诗歌爱好者阅览投稿!喜欢本站的话请大家把本站告诉给你朋友哦!地址是 www.qingshiwang.com !