Rust in Everything
基于 axum 0.8.9

axum 源码解析

这一卷对着 axum 0.8.9(tag axum-v0.8.9,commit c59208c8)读源码,同仓库的 axum-core(按 crates.io 实际编译的 0.5.6,tag axum-core-v0.5.6)和 axum-macros 0.5.1 一起讲;tower-http 只讲 Web 应用最常用的几个中间件,版本 0.7.1(tag tower-http-0.7.1)。所有源码链接都指向这几个 tag。

axum 不碰字节。连接、HTTP 协议、axum::serve 底下的 accept 循环都在 hyper 卷;Router、MethodRouter、Route 都是 tower 的 Service,.layer(...) 用的就是 tower 的 Layer(tower 卷)。axum 自己做的事分在两个时刻:

  • 装配主线(启动时,类型在变):async fn 因为 Handler trait 的宏实现成为 handler,get(handler) 把它放进 MethodRouter 的方法槽,Router::route 把路径插进 matchit 路由树,.layer 套中间件,.with_state 交出状态,Router<S> 变成 Router<()>。
  • 请求主线(每个请求,值在流动):Router::call 用 matchit 匹配路径,MethodRouter 按方法选端点,Route 调用装箱的服务,handler 依次跑提取器,最后把返回值 into_response()。
flowchart TB
  intro[00 导读] --> overview[01 全景]
  overview --> handler[02 Handler 与提取器]
  handler --> resp[03 响应]
  resp --> routing[04 路由]
  routing --> mw[05 中间件]
  mw --> thttp[06 tower-http]
  routing --> ws[07 WebSocket]
  mw --> testing[08 测试]
  thttp --> design[09 设计取舍]
  ws --> design
  testing --> design
  design --> pit[10 常见坑]
  pit --> site[11 在本站中]
  site --> hands[12 动手]

从「导读」开始。只想会用 axum 的读者,读 01 全景、02 Handler 与提取器、04 路由和常见坑;想读懂实现的,按顺序读,02 是全卷的重点:axum 和其他 Web 框架最不一样的地方在那里,常见的编译错误也大半出在那里。

💬 关联讨论

发起讨论
加载中...