How do I create a URL shortener?

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

    For a quality Node.js / JavaScript solution, see the id-shortener module, which is thoroughly tested and has been used in production for months.

    It provides an efficient id / URL shortener backed by pluggable storage defaulting to Redis, and you can even customize your short id character set and whether or not shortening is idempotent. This is an important distinction that not all URL shorteners take into account.

    In relation to other answers here, this module implements the Marcel Jackwerth's excellent accepted answer above.

    The core of the solution is provided by the following Redis Lua snippet:

    local sequence = redis.call('incr', KEYS[1])
    
    local chars = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz'
    local remaining = sequence
    local slug = ''
    
    while (remaining > 0) do
      local d = (remaining % 60)
      local character = string.sub(chars, d + 1, d + 1)
    
      slug = character .. slug
      remaining = (remaining - d) / 60
    end
    
    redis.call('hset', KEYS[2], slug, ARGV[1])
    
    return slug
    

提交回复
热议问题