Skip to content

Instantly share code, notes, and snippets.

@danveloper
Created November 8, 2012 21:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danveloper/4041963 to your computer and use it in GitHub Desktop.
Save danveloper/4041963 to your computer and use it in GitHub Desktop.
The 48-Line Volatile URL Shortener
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
}
}
}
}
}
@danveloper
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment