How do I create a URL shortener?

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

    A Node.js and MongoDB solution

    Since we know the format that MongoDB uses to create a new ObjectId with 12 bytes.

    • a 4-byte value representing the seconds since the Unix epoch,
    • a 3-byte machine identifier,
    • a 2-byte process id
    • a 3-byte counter (in your machine), starting with a random value.

    Example (I choose a random sequence) a1b2c3d4e5f6g7h8i9j1k2l3

    • a1b2c3d4 represents the seconds since the Unix epoch,
    • 4e5f6g7 represents machine identifier,
    • h8i9 represents process id
    • j1k2l3 represents the counter, starting with a random value.

    Since the counter will be unique if we are storing the data in the same machine we can get it with no doubts that it will be duplicate.

    So the short URL will be the counter and here is a code snippet assuming that your server is running properly.

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    // Create a schema
    const shortUrl = new Schema({
        long_url: { type: String, required: true },
        short_url: { type: String, required: true, unique: true },
      });
    const ShortUrl = mongoose.model('ShortUrl', shortUrl);
    
    // The user can request to get a short URL by providing a long URL using a form
    
    app.post('/shorten', function(req ,res){
        // Create a new shortUrl */
        // The submit form has an input with longURL as its name attribute.
        const longUrl = req.body["longURL"];
        const newUrl = ShortUrl({
            long_url : longUrl,
            short_url : "",
        });
        const shortUrl = newUrl._id.toString().slice(-6);
        newUrl.short_url = shortUrl;
        console.log(newUrl);
        newUrl.save(function(err){
            console.log("the new URL is added");
        })
    });
    

提交回复
热议问题