अंतिम अद्यतन:2026-10-12
C++ short URL service Demo¶
असली short URLs तुलनात्मक रूप से काफी जटिल होते हैं, उदाहरण के लिए: hash algorithm, number issuing system आदि।
आज बस एक छोटे project के नज़रिए से short URL का implementation simulate करते हैं।
मात्र कुछ दर्जन lines के code से इसे जल्दी कैसे implement करें? इसमें शामिल कुछ key points:
- Long URL को छोटा कैसे करें
- Mapping relationship को कैसे store करें
Mapping relationship की बात तो सरल है, एक map से in-memory persistence, अगर database जुड़ी हो, तो database के jdbc/odbc जैसे interfaces से लिखकर database में डालना होगा।
Long URL को छोटा करने के लिए यहाँ random algorithm + fixed length वाले idea से implementation की गई है।
1. Random¶
uniform_int_distribution से एक [a, b] interval का random number generate किया जाता है, यहाँ हर बार नीचे दी string में से एक character लिया जाता है, और अंत में जोड़ने पर short URL बन जाता है।
इसमें शामिल हैं:
- Digits
- lowercase letters
- uppercase letters
uniform_int_distribution<int> distribution(0, characters.size() - 1);
string code;
for (int i = 0; i < length; ++i)
code += characters[distribution(generator)];
2. Storage¶
हर बार इसे map में store कर दें, उदाहरण के लिए:
if (links.count(originalLink)) {
return links[originalLink];
}
shortCode = generateRandomCode(len);
string shortenedLink = base_url + shortCode;
links[shortenedLink] = originalLink;
यहाँ base url रखा गया है, उदाहरण के लिए:
string baseUrl = "https://www.google.com.hk/search";
LinkShortener shortener(baseUrl);
string originalLink = "https://www.google.com.hk/search?q=asdsad&oq=asdsad&aqs=chrome.0.69i59j69i57j69i59l2.634j0j4&sourceid=chrome&ie=UTF-8";
string shortenedLink = shortener.shortenLink(originalLink, 8);
अंत में इस url को छोटा किया जा सकता है:
बहुत सरल है न? इस section के tests और पूरा code 星球 पर अपडेट किए जा चुके हैं, join करके साथ सीखने-बढ़ने के लिए स्वागत है~
संबंधित विषय¶
- खुद C++ FnOnce लिखना | C++那些事
- C++ gRPC छोटा project | C++那些事
- C++ inter-process communication व्यवहार | C++那些事
- C++17 और SQLite से directory का size निकालना | C++那些事
- Google Benchmark performance testing | C++那些事
- C++20 coroutine HTTP server | C++那些事
- Protobuf ZeroCopy serialization | C++那些事
- pybind11 से Python तेज़ करना | C++那些事
- C++ stack calculator design | C++那些事