- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 347字
- 2021-06-24 17:04:27
Reader's challenge – an API for URL shortening
With all the basics you have learned up to now, try to implement a URL shortening service. A URL shortener takes a very long URL and returns a shortened, crisp, and memorable URL back to the user. At first sight, it looks like magic, but it is a simple math trick.
In a single statement, URL shortening services are built upon two things:
- A string mapping algorithm to map long strings to short strings (Base 62)
- A simple web server that redirects a short URL to the original URL
There are a few obvious advantages of URL shortening:
- Users can remember the URL; easy to maintain
- Users can use the links where there are restrictions on text length, for example, Twitter
- Predictable shortened URL length
Take a look at the following diagram:
Under the hood, the following things happen in a URL shortening service:
- Take the original URL
- Apply BASE62 encoding on it; it generates a Shortened URL
- Store that URL in the database. Map it to the original URL ([shortened_url: original_url])
- Whenever a request comes to the shortened URL, just do an HTTP redirect to the original URL
We will implement a full example in upcoming chapters when we integrate databases to our API server, but before that, though, we should specify the API design documentation.
Take a look at the following table:
URL REST Verb Action Success Failure
/api/v1/new POST Create a shortened URL 200 500, 404
/api/v1/:url GET Redirect to original URL 301 404
You can use a dummy JSON file/Go map to store the URL for now instead of a database.
推薦閱讀
- 演進(jìn)式架構(gòu)(原書第2版)
- 嵌入式軟件系統(tǒng)測試:基于形式化方法的自動化測試解決方案
- Monkey Game Development:Beginner's Guide
- 深度學(xué)習(xí)經(jīng)典案例解析:基于MATLAB
- MATLAB圖像處理超級學(xué)習(xí)手冊
- 深入理解Django:框架內(nèi)幕與實現(xiàn)原理
- MATLAB 2020 從入門到精通
- Essential Angular
- MongoDB權(quán)威指南(第3版)
- 信息技術(shù)應(yīng)用基礎(chǔ)
- Visual C#通用范例開發(fā)金典
- Swift細(xì)致入門與最佳實踐
- 深入理解C指針
- Java程序設(shè)計基礎(chǔ)(第6版)
- Microsoft Dynamics GP 2013 Cookbook