I am using Axum as my rust web server. Users can make get requests and supply a page number for pagination purposes.
I am trying to figure out what the correct and efficient approach is to return back the "current" uri
except with next page number.
For example, users can first retrieve:
http://localhost:8080/posts?sort=top&time=24h
In my response json, I need to return same uri but with next page number:
/posts?sort=top&time=24h&page=2
/posts?sort=top&time=24h&page=3
and so on.
I am able to retrieve the uri using request.uri()
in my handler. But what's the most efficient way for me to return the same uri but only a single query parameter being different?
The most straightforward way would be to have a struct that represents the parsed query string and that implements Deserialize
and Serialize
. Doing it this way has several advantages:
Query
instead of manually parsing it.For example:
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
enum Sort {
Top,
Bottom,
}
#[derive(Deserialize, Serialize)]
struct PostsQuery {
pub sort: Sort,
pub time: String, // Or some other type that represents the parsed state?
pub page: usize,
}
Now you can extract Query<PostsQuery>
.
To serialize it back to a query string, you can use the serde_urlencoded crate, which is what Query
uses to deserialize the query string.
async fn handler(Query(mut query): Query<PostsQuery>) {
query.page += 1;
let query_string = serde_urlencoded::to_string(&query);
// Now use query_string in construction of the URL.
}