Rust Macros Rule: DRY warp Routes

submited by
Style Pass
2021-05-21 14:30:13

The backend for A Viral World is written in Rust using the warp web server , which I chose for how lightweight, feature-filled, and well-maintained it is. All the server routes are contained in a single module. Here’s an example of what they used to look like:

The only unique parts of each route are the handler, the path, and the HTTP method. There was no need for the repetition, and none of it was warp’s fault. It was all convoluted code born out of inexperience. Now that I was more familiar with Rust in general and warp in particular, I could mold it into something more pleasing.

This could be better written as a collection (a Vec, in this case) that could be combined using Iterator::fold . The naïve approach wouldn’t work, however:[1]

Leave a Comment