

Axum框架自动处理请求的神奇函数
source link: https://www.jdon.com/62919
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Axum框架自动处理请求的神奇函数
让我们探讨一下处理函数在编程语言中通常的样子。这里有一些例子:
let app = Router::new() .route("/users", get(users)) .route("/products", get(product)); async fn users(req: Request) -> Response { let params = Query<Params>::from_request(&req); /* ... */ } async fn product(req: Request) -> Response { let db = State<Db>::from_request(&req); let data = Json<Payload>::from_request(&req); /* ... */ } |
你得到一个Request类型作为输入,并返回一个Response。Request参数也可以用来从请求中提取更多的数据,如有效载荷。这种方法的主要优点是,它相当简单易懂,并且很好地映射到实际的客户/服务器模式。这里没有太多的魔力,一切都很明确,而且很容易围绕它形成一个心理模型。
Rust的开发者通常喜欢这些特性,可预测性和明确性,而不是魔法。这就是为什么我对大多数Rust网络框架走另一条路线感到相当惊讶。让我们来看看!
神奇的处理函数
Rust 中的“神奇处理函数”是什么?
它们是签名决定从Request结构中提取什么和如何提取的函数。
用一个例子来解释它们更容易。让我们看看下面的Axum代码:
let app = Router::new() .route("/users", get(users)) .route("/products", get(product)); async fn users(Query(params): Query<Params>) -> impl IntoResponse { /* ... */ } async fn product(State(db): State<Db>, data: Json<Payload>) -> String { /* ... */ } |
注意到传递给路由器的处理函数有不同数量的参数和不同的参数类型,但神奇的是它们被变成了正确的值。例如,数据将包含被解析为Json类型的有效载荷。
这些函数向开发者隐藏了很多信息,从性能特征到错误处理行为。
详细点击标题
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK