Banged my head against the wall for a bit on how to have dynamic blog routes on Write.as, so we can support custom redirects (as might be needed when moving from another platform to ours).
I dug into Go’s
http library for a bit, then came across this Stack Overflow answer that pointed me in the right direction. Then it was a matter of how I’d make this multi-user and entirely dynamic, loading rules from the database for any blog that had redirect rules. For a minute, I was just going to hard-code things for the single blog that needs this feature to avoid more database overhead, but even that got messy, and it was better to do it right.
My solution was this: when the app starts up (and initializes all routes), query the database for all blogs with custom redirect rules. Then for each one, add a special handler that runs through all the custom rules for that blog. This handler only applies to the blog’s canonical URL (e.g. a custom domain) to keep things simple.
from path (the old URL we’re redirecting from) matches the address the visitor navigated to, move on to handling the request. There, we again match the
from path to the current URL, and expand it into the desired
to path (the destination) with any regex variables replaced — and finally redirect the user. This maintains support for regular expressions in these redirect rules, and most importantly, doesn’t add new overhead for other users or valid URLs. Phew, that was a challenge. But I’m pleased with the results!