Created
December 1, 2011 11:03
-
-
Save Luit/1415852 to your computer and use it in GitHub Desktop.
A very ugly first version of a URL shortening service written in VCL inline C. There's a whole lot still to be done, but this thing works quite well already.
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
C{ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <hiredis/hiredis.h> | |
}C | |
sub vcl_recv { | |
if (req.http.host ~ "(?i)^a.luit.it$") { | |
if (req.url ~ "(?i)^/l/.*[A-Za-z0-9\-_]{4,}\+?$") { | |
set req.url = regsub(req.url, | |
"(?i)(.*/)+([A-Za-z0-9\-_]{4}[A-Za-z0-9\-_]*)\+?$", "\2"); | |
C{ | |
redisContext *c; | |
redisReply *reply; | |
//c = redisConnectUnix("/var/run/redis/redis.sock"); | |
c = redisConnect("127.0.0.1", 6379); | |
if (c->err) { | |
VRT_error(sp, 751, c->errstr); | |
} else { | |
char key[32]; // SHA1 hash in b64 plus some extra | |
char keykey[3]; | |
strncpy(key, VRT_r_req_url(sp), 31); | |
key[31] = '\0'; | |
strncpy(keykey, key, 2); | |
keykey[2] = '\0'; | |
reply = redisCommand(c, "HGET shortener-%s %s", keykey, key + 2); | |
if (reply->type == REDIS_REPLY_STRING) { | |
VRT_error(sp, 750, reply->str); | |
} else if (reply->type == REDIS_REPLY_NIL) { | |
VRT_error(sp, 754, key); | |
} else { | |
VRT_error(sp, 752, reply->str); | |
} | |
freeReplyObject(reply); | |
redisFree(c); | |
} | |
}C | |
return (error); | |
} | |
error 404; | |
} | |
} | |
sub vcl_error { | |
if (obj.status == 754) { | |
set obj.status = 404; | |
set obj.response = "Not Found"; | |
synthetic {"Short URL code "} + req.url + {" not found"}; | |
return (deliver); | |
} | |
if (obj.status == 751 || obj.status == 752) { | |
set obj.status = 500; | |
synthetic {"Having trouble with Redis: "} + obj.response; | |
set obj.http.X-Redis-Error = obj.response; | |
set obj.response = "Internal Server Error"; | |
return (deliver); | |
} | |
if (obj.status == 750) { | |
set obj.http.Location = obj.response; | |
# Probably should make this 301 Moved Permanently in the end | |
set obj.status = 302; | |
set obj.response = "Found"; | |
return (deliver); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment