How to use “Type safe routing” of axum
The article will show you how to use the “Type safe routing” of axum.
axum
is a web application framework of Rust.
You should be familiar a little with the axum for better understanding.
At the first step we create a normal Router.
A problem with normal routing, is that string the wrong path parameters results in a run-time error.
Specifically, "/api/users/:user_id"
and ”/api/users/:user_i"
both be success compile. At that moment, run-time error looks like…
⫸ curl localhost:8088/api/users/123
Invalid URL: missing field `user_id`
“Type safe routing” is solution to the problem.
Code looks like the below
In the case, if "/api/users/:user_id"
is ”/api/users/:user_i"
, then to be compile error like this.
error[E0026]: struct `PathParam` does not have a field named `user_i`
--> src/main.rs:71:14
|
71 | #[typed_path("/api/users/:user_i")]
| ^^^^^^^^^^^^^^^^^^^^
| |
| struct `PathParam` does not have this field
| help: a field with a similar name exists: `user_id`
By the way, the correct response is this.
⫸ curl localhost:8088/api/users/123
{"user_id":"123"}
This is a little use case. Hopefully, the article will help you.