Created
November 8, 2012 21:55
-
-
Save danveloper/4041963 to your computer and use it in GitHub Desktop.
The 48-Line Volatile URL Shortener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.ServerSocket | |
def socket = 8281, password = "danrulz" | |
enum Database { | |
INSTANCE; | |
def table = [:] | |
def shortCodeTable = [:] | |
def insert = { String url -> | |
Sequence.INSTANCE.counter++ | |
def id = Sequence.INSTANCE.counter | |
def shortCode = new BigInteger(id).toString(36)+BigInteger.valueOf(Math.round(Math.random()*1000)).toString(36) | |
table.put(id, [url: url, shortCode: shortCode]); | |
shortCodeTable.put(shortCode, id) | |
return id | |
} | |
def load = { id -> table.get(id) } | |
def findUrlByShortUrl = { uri -> | |
return load(shortCodeTable.get(uri))?.url | |
} | |
} | |
enum Sequence { | |
INSTANCE; | |
def counter = 1000 | |
} | |
def server = new ServerSocket(socket), running = true | |
while(running) { | |
server.accept { s -> | |
s.withStreams { i, o -> | |
def r = i.newReader() | |
def b = r.readLine() | |
if (b.startsWith("GET")) { | |
def m = b =~ /^GET \/(.*) HTTP\/1\.1/ | |
def uri = m[0][1] | |
def url = Database.INSTANCE.findUrlByShortUrl(uri) | |
o << "HTTP/1.1 301 Moved Permenantly\nLocation: $url\n\n" | |
} else if (b.startsWith("UPDATE")) { | |
def m = b =~ /^UPDATE (.*) HTTP\/1\.1/ | |
def id = Database.INSTANCE.insert(m[0][1]) | |
def shortCode = Database.INSTANCE.load(id)?.shortCode | |
o << "{ \"code\": \"$shortCode\" }\n\n" | |
} else if (b.startsWith("PATCH")) { | |
def m = b =~ /^PATCH (.*) HTTP\/1\.1/ | |
if (password.equals(m[0][1])) { | |
running = false | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add URLs to the database using the HTTP UPDATE METHOD!!
$ telnet localhost 8281
Trying ::1...
Connected to localhost.
Escape character is '^]'.
UPDATE http://www.yetanothercrappybloghostingprovider.com/really/long/blog/posting HTTP/1.1
{ "code": "rt3c" }
Connection closed by foreign host.
Get redirected with standard HTTP forward codes!!
[ddcdwoods@mbp-ddcdwoods /]$ telnet localhost 8281
Trying ::1...
Connected to localhost.
Escape character is '^]'.
GET /rt3c HTTP/1.1
HTTP/1.1 301 Moved Permanently
Location: http://www.yetanothercrappybloghostingprovider.com/really/long/blog/posting
Connection closed by foreign host.
Open your browser and notice redirection working!!
http://localhost:8281/rt3c --> http://www.yetanothercrappybloghostingprovider.com/really/long/blog/posting
AMAZING!!!
g: daniel.p.woods@gmail.com ... t: @danveloper