How do I create a URL shortener?

后端 未结 30 2463
我寻月下人不归
我寻月下人不归 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:27

    I keep incrementing an integer sequence per domain in the database and use Hashids to encode the integer into a URL path.

    static hashids = Hashids(salt = "my app rocks", minSize = 6)
    

    I ran a script to see how long it takes until it exhausts the character length. For six characters it can do 164,916,224 links and then goes up to seven characters. Bitly uses seven characters. Under five characters looks weird to me.

    Hashids can decode the URL path back to a integer but a simpler solution is to use the entire short link sho.rt/ka8ds3 as a primary key.

    Here is the full concept:

    function addDomain(domain) {
        table("domains").insert("domain", domain, "seq", 0)
    }
    
    function addURL(domain, longURL) {
        seq = table("domains").where("domain = ?", domain).increment("seq")
        shortURL = domain + "/" + hashids.encode(seq)
        table("links").insert("short", shortURL, "long", longURL)
        return shortURL
    }
    
    // GET /:hashcode
    function handleRequest(req, res) {
        shortURL = req.host + "/" + req.param("hashcode")
        longURL = table("links").where("short = ?", shortURL).get("long")
        res.redirect(301, longURL)
    }
    

提交回复
热议问题