Skip to content

Instantly share code, notes, and snippets.

@perbu
Created May 11, 2016 09:50
Show Gist options
  • Save perbu/b00c7687b40dd00b60d0e5c13b6f766c to your computer and use it in GitHub Desktop.
Save perbu/b00c7687b40dd00b60d0e5c13b6f766c to your computer and use it in GitHub Desktop.
vcl 4.0;
import curl;
import cookie;
import std;
backend default {
.host = "127.0.0.1";
.port = "8000";
}
sub vcl_recv {
cookie.parse(req.http.Cookie);
# Set a UID so we don't rely on GA
if (cookie.get("uid")) {
set req.http.uid = cookie.get("uid");
} else {
set req.http.uid = std.random(1,1000000);
}
if (cookie.get("abgroup")) {
std.log("User is already assigned");
set req.http.abgroup = cookie.get("abgroup");
if (req.http.abgroup !~ "A|B") {
# if the user has an invalid value, just force A.
std.log("Invalid group. Forcing value...");
set req.http.abgroup = "A";
}
} else {
# assign the user to A or B using external service
curl.get("http://localhost:8080/uid=" + req.http.uid);
set req.http.abgroup = curl.header("X-decision");
curl.free();
std.log("Callout decided user " +req.http.uid +" is in category " + req.http.abgroup);
}
}
sub vcl_deliver {
if (req.http.abgroup) {
set resp.http.Set-Cookie = "abgroup=" + req.http.abgroup +
";uid=" + req.http.uid + "; Expires=" +
cookie.format_rfc1123(now, 10m) + "; httpOnly";
# mostly for debugging
set resp.http.abgroup = req.http.abgroup;
set resp.http.uid = req.http.uid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment