当前位置:   article > 正文

基于Rust的Web开发,actix的基本使用_rust actix

rust actix

rust-web

Rust语言开发的web系统,常见的web框架主要有:Rocket(必须使用Rust nightly版本)、Actix、Yew(结合WebAssembly使用较好)、Warp等

这里不对以上框架做优缺点比较,因为自己涉猎也比较浅,所以不知道,则不评价,仅仅是因为自己会简单使用Actix,所以这里对Rust中使用Actix做简单分享。

环境搭建

首先,需要引入相关依赖

actix-web = "4"
env_logger = "0.9"
serde = {version = "1.0",features = ["derive"]}
  • 1
  • 2
  • 3

这里指定serde的版本和特性,是因为在Rust高版本中需要用到,否则在使用结构体序列化时候,会编译报错(如下图):

在这里插入图片描述
那么接下来就是直接使用了,Actix提供了简单的开箱即用的一些方法,便于直接构建一个web项目。下面是简单的代码示例:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Logger::default())
            .service(web::resource("/hello").to(index))
    })
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

这里需要把main函数设置为异步的,前面2行代码是基本的日志打印相关设置。

主要这里直接new了一个HttpServer实例,绑定在了本机的8080端口上,然后运行等待。

创建HttpServer实例,传入一个无参闭包

闭包函数创建了APP实例,并监听了/hello服务,同时将这个/hello服务,指定index服务函数处理

这里贴出来index函数处理/hello服务:

/*无参请求*/
async fn index(req: HttpRequest) -> &'static str {
    println!("REQ:{req:?}");
    "hello world"
}
  • 1
  • 2
  • 3
  • 4
  • 5

处理该请求,打印了请求的一些信息,同时返回了字符串“hello world”

启动main函数,监听localhost的8080端口开始,调用http://localhost:8080/hello,将得到以下结果:

在这里插入图片描述

url路径参数传递

这里简单举例类似/XXX/{param},url连接get请求参数传递方式

开启一个新的service监听服务:

.service(web::resource("/getByInput/{name}").to(return_result))
  • 1

定义return_result函数

/*url带参数请求 /getByInput/{2323} */
async fn return_result(str: web::Path<String>, req: HttpRequest) -> impl Responder {
    println!("REQ:{req:?}");
    format!("Hello {}!", str)
}
  • 1
  • 2
  • 3
  • 4
  • 5

参数以为web::Path类型作为后台接收

运行效果:

在这里插入图片描述
这里非常喜欢Actix对于中文字符的处理,即使用的时候,不需要添加多余的处理方式,轻松得到没有乱码的数据。

get请求参数传递

添加一个新的服务监听:

.service(web::resource("/getReq").route(web::get().to(get_return)))
  • 1

这里用web::get(),明确指定了请求/getReq为get请求,以其他方式的调用,均是不允许的

同时需要创建一个结构体,用于接收参数

#[derive(Serialize,Deserialize)]
struct Param {
    name: String,
    password: String,
}
  • 1
  • 2
  • 3
  • 4
  • 5

上面结构体Param指定自定义序列化宏,是因为Actix中接收参数必须使用。
定义get_return函数

/*get带参数请求 /getReq?name=依荨&password=123456 */
async fn get_return(param : web ::Query<Param>
                    ,req:HttpRequest) -> impl Responder {
    println!("REQ:{req:?}");
    format!("Your name is {},and Your password is {}", param.name,param.password)
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

运行效果:

在这里插入图片描述

post请求表单参数传递

运行效果:

在这里插入图片描述

post请求Json参数传递

运行效果:

在这里插入图片描述

这里省略的内容,请关注“依荨”,H(回)F(复) Actix,get all content

有Rust入门学习笔记,轻轻松松学习Rust

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/889178
推荐阅读
相关标签
  

闽ICP备14008679号