要说最近几年什么语言热度最高,必然绕不过去rust,无论什么领域都能看到“用rust重写xxx”的repo出现。其实22年我就计划学习这门语言,不过那段时间给自己找的借口太多了,一直都没有开始学习,最近手上几个项目都不算忙,遂打算开始入坑rust,争取以后自己也能用rust重写一个小玩意出来。
本着从实践出发的原则,加上我写的大多数项目都是web领域,所以这次打算从web开发开始入坑。先简单看了一天语法后,我就打算使用rust web开发明星项目axum来入门。从axum - Rust文档开始第一个HelloWorld程序。
use axum::{
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
大多数web框架在启动完服务之后,第一步要处理的事情就是路由匹配与参数获取,axum通过创建Router来指定路径,其中对于同一个路径可以有多个响应函数处理,不过这些响应函数都要被包裹在axum:routing::get、axum:routing::post等方法中,用于指定响应的请求类型,例如下面这个代码就表示同时响应get和post两种请求方式:
pub async fn hello_world() -> &'static str {
"Hello, World!"
}
Router::new().route("/", get(hello_world).post(hello_world))
如果想要获取参数,则可以使用Path、Query或者Json等结构体,分别用来获取path参数、query参数和body中的application/json类型的参数,例如:
pub async fn query_params(Query(params): Query<QueryDataStruct>) -> Json<QueryDataStruct> {
axum::Json(params)
}
pub async fn path_params(Path(id): Path<i32>) -> String {
format!("path params: {}", id)
}
pub async fn json_params(Json(body): Json<BodyDataStruct>) -> Json<BodyDataStruct> {
axum::Json(body)
}
除此之外,我们还经常会从headers中获取参数,在axum中我们可以使用HeaderMap获取:
pub async fn header_params(headers: HeaderMap) -> String {
let agent = headers.get("User-Agent").unwrap();
format!("Header User-Agent: {:?}",agent)
}
暂时学到这里,明天继续😁
吐槽一下,rust确实小众了点,加标签的时候发现axum、tokio都没有,但是能搜到spring全家桶😂
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。