Skip to content

Instantly share code, notes, and snippets.

@davepeck
Created January 25, 2023 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davepeck/4b62f3a1cb423b1f2ebbd098068f3c41 to your computer and use it in GitHub Desktop.
Save davepeck/4b62f3a1cb423b1f2ebbd098068f3c41 to your computer and use it in GitHub Desktop.
My first cloudfront edge function
// note that a lot of code choices here are due to the fact that cloudfront edge uses
// a hilariously backwards version of javascript:
//
// "const", you say? what's that?!
// deal with the painful structure that cloudfront edge functions use for query params
function getURLSearchParamsString(obj) {
var str = [];
for (var param in obj) {
if (obj[param].multiValue) {
str.push(
obj[param].multiValue.map((item) => param + "=" + item.value).join("&")
);
} else if (obj[param].value === "") {
str.push(param);
} else {
str.push(param + "=" + obj[param].value);
}
}
return str.join("&");
}
// redirect the following URL sub-paths to somewhere else
// this is for my fancy personalized mastodon setup; see https://til.simonwillison.net/mastodon/custom-domain-mastodon
// and the articles it links to. most of those happen to deploy their site with Django which... would have been
// easier than writing, testing, and installing this function into CloudFront. But I persist for now! :-)
function handler(event) {
var paths = ["/.well-known/host-meta", "/.well-known/webfinger", "/.well-known/nodeinfo"];
var baseUrl = "https://mastodon.davepeck.org";
var request = event.request;
var uri = request.uri;
var matches = paths.filter(path => uri.startsWith(path));
if (matches.length === 1) {
var qs = getURLSearchParamsString(request.querystring);
var qp = qs ? `?${qs}` : "";
var location = `${baseUrl}${matches[0]}${qp}`;
var response = {
statusCode: 301,
statusDescription: "Found",
headers: {"location": {"value": location}}
};
return response;
}
return request;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment