Rust: Web框架Axum和Rest Client协同测试

[复制链接]
发表于 2026-1-27 15:27:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
Axum作为Rust当红Web框架,值得相识一下。下面实例包罗几个范例的常场场景。
具体如下:
一、Axum
1、toml中依赖
  1. [dependencies]
  2. tokio = {version="1.39.3",features =["full"]}
  3. axum ={version ="0.7.5",features =["tokio"]}
  4. serde = {version ="1.0.209",features =["derive"]}
  5. serde_json ="1.0.1"
复制代码
2、main.rs
涉及到简单路由和提取器等,包罗紧张范例的文件形态的处置处罚。
  1. use axum::{
  2.     routing::{get,post},
  3.     Router,
  4.     response,
  5.     Form,
  6.     http::{header::HeaderMap},
  7. };
  8. use serde_json::{Value, json};
  9. use serde::Deserialize;
  10. use axum::extract::{ Query,Json,Path};
  11. use std::collections::HashMap;
  12. use std::sync::Arc;
  13. #[derive(Deserialize,Debug)]
  14. struct User {
  15.     name: String,
  16.     old: i32,
  17. }
  18. #[derive(Deserialize)]
  19. struct LoginForm {
  20.     account: String,
  21.     password: String,
  22. }
  23. #[derive(Deserialize,Debug)]
  24. struct Params {
  25.     tradedays: Option<i32>,//Option=>字段可以缺省
  26.     price:Option<f64>,
  27.     name: Option<String>,
  28. }
  29. #[derive(Deserialize,Debug)]
  30. struct Strategy {
  31.     name: String,
  32.     amount: f64,
  33.     id: i32,
  34. }
  35. #[derive(Debug)]
  36. struct AppState {
  37.     count: i32
  38. }
  39. #[tokio::main]
  40. async fn main() {
  41.     let shared_state = Arc::new(AppState { count:0 });
  42.     let app = Router::new()
  43.         .route("/", get(hello))
  44.         .route("/headers",get(headers))
  45.         .route("/html", get(hello_html))
  46.         .route("/form", get(show_form).post(accept_form))
  47.         .route("/hashmap", get(query_hashmap))//全部解释成hashmap
  48.         .route("/user/:name/:old", get(query_user))
  49.         .route("/path/:name/:id", get(path)) //两个参数
  50.         .route("/json", post(query_user_json))
  51.         .route("/query_json",post(
  52.              {
  53.                 let shared_state = Arc::clone(&shared_state);
  54.                 move |body| query_json(body,shared_state)
  55.              }   
  56.         ,))
  57.         .route("/params",get(get_params))
  58.         .route("/strategies/", get(query_strategy));
  59.     println!("Serving on http://localhost:8080 ...");
  60.     let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await.unwrap();
  61.     axum::serve(listener, app).await.unwrap();
  62. }
  63. async fn headers(headers: HeaderMap) ->String{
  64.     format!("{:?}", headers)
  65. }
  66. // Query: ?和=来解析
  67. async fn get_params(Query(params): Query<Params>) -> String {
  68.     let tradedays = params.tradedays.unwrap_or(0);
  69.     let price = params.price.unwrap_or(0.0);
  70.     let name = params.name.unwrap_or("no name".to_string());
  71.     format!("tradedays {:?}, price: {:?}  name:{:?}", tradedays, price,name)
  72. }
  73. //多个复杂的参数
  74. async fn query_strategy(Json(strategy): Json<Strategy>) ->String{
  75.     println!("strategy :{:?}",strategy);
  76.     format!("receive=> strategy:{:?}",strategy)
  77. }
  78. //Json(user):Json<User>
  79. async fn query_hashmap(Query(inputs): Query<HashMap<String, String>>) -> String{
  80.     println!("inputs:{:?}",inputs);
  81.     format!("inputs:{:?}",inputs)
  82. }
  83. async fn query_user(Path(user):Path<User>){
  84.     println!("welcome! user:{user:#?}");
  85. }
  86. async fn query_user_json(Json(user): Json<User>) -> response::Json<Value>{
  87.     println!("response:{:?}",user);
  88.     Json(json!({ "user": user.name, "old": user.old }))
  89. }
  90. async fn query_json(Json(user):Json<User>,arc: Arc<AppState>)->String{
  91.     println!("arc:{:?}",arc);
  92.     format!("user:{:?} ",user)
  93. }
  94. // `&'static str` becomes a `200 OK` with `content-type: text/plain; charset=utf-8`
  95. async fn hello() -> &'static str {
  96.     "Hello, World!"
  97. }
  98. async fn path(Path((name,id)):Path<(String,i32)>) ->String{
  99.     println!("hi,{name:#?} => id {id:#?}");
  100.     format!("hi,{},{}",name,id)
  101.    
  102. }
  103. // `Html` will get a `text/html` content-type
  104. async fn hello_html() -> response::Html<&'static str> {
  105.     response::Html("
  106.         <h1>Hello HTML</h1>
  107.         <p>Hello, World!</p>
  108.     ")
  109. }
  110. async fn show_form() -> response::Html<&'static str> {
  111.     response::Html(r#"
  112.         <html>
  113.         <head>
  114.             <title>Login Form</title>
  115.         </head>
  116.         <body>
  117.             <h1>User Info</h1>
  118.             <form method="post">
  119.                 <label for="field1">account:</label>
  120.                 <input type="text" name="field1" id="field1"><br>
  121.                 <label for="field2">password:</label>
  122.                 <input type="text" name="field2" id="field2"><br>
  123.                 <input type="submit" value="Submit">
  124.             </form>
  125.         </body>
  126.         </html>
  127.     "#)
  128. }
  129. async fn accept_form(Form(login): Form<LoginForm>) -> response::Html<String> {
  130.     let response_html = format!(
  131.         r#"
  132.         <html>
  133.         <head>
  134.             <title>Form Submission Result</title>
  135.         </head>
  136.         <body>
  137.             <h1>Form Submission Result</h1>
  138.             <p>account : {}</p>
  139.             <p>password: {}</p>
  140.         </body>
  141.         </html>
  142.     "#,
  143.         login.account, login.password);
  144.    
  145.     println!("response_html: {}", response_html);
  146.     response::Html(response_html)
  147. }
复制代码
二、Rest Client工具协同测试
在vscode中下载Rest Client插件后,通过创建以.http 或 .rest为末端的文件,举行http哀求测试。具体Rest Client功能很强盛,这里只先容,与Axum共同测试的方案。
具体如下:
  1. # 头文件和body之间要有空隔行
  2. ### 值中不需要引号!
  3. @url = http://localhost:8080
  4. @name = wowotuo
  5. @token =ad;ipiqedqeqeqeqepqei1213132;dkqdqeqe
  6. @id =6
  7. ### =>"/";GET;
  8. GET {{url}}/ HTTP/1.1
  9. ### =>"/html";GET
  10. GET {{url}}/html HTTP/1.1
  11. ### /headers
  12. GET {{url}}/headers  HTTP/1.1
  13. ### /path/:name/:id ; id为输入参数
  14. GET {{url}}/path/{{name}}/{{id}} HTTP/1.1
  15. ### =>/form;有GET和POST两部分;POST方法要求输入
  16. POST {{url}}/form HTTP/1.1
  17. Content-Type: application/x-www-form-urlencoded
  18. account={{name}}&password=dbfund
  19. ### /json; POST.输入user的json格式; 注意JSON格式要"双引号"!
  20. POST {{url}}/json HTTP/1.1
  21. content-type: application/json; charset=utf-8
  22. {
  23.     "name": "{{name}} 你好!",
  24.     "old": 19
  25. }
  26. ### /user/:name/:old; 另外一种表达形式
  27. GET {{url}}/user/{{name}}/32  HTTP/1.1
  28. ### /params
  29. GET {{url}}/params?tradedays=3&price=3.9&name=breaking
  30. ### /hashmap; POST,要求输入hashmap
  31. GET {{url}}/hashmap?name={{name}}&old="19"  HTTP/1.1
  32. ### 对于curl命令的支持 类似 =>GET {{url}}/html
  33. curl --request GET \
  34.      --url {{url}}/html
  35. ###--header 'user-agent: vscode-restclient'
复制代码
三、输出
用Rest Client调试的效果好坏常直观。

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表