位置: IT常识 - 正文

【一起学Rust | 框架篇 | Viz框架】轻量级 Web 框架——Viz(rust 入门教程)

编辑:rootadmin
【一起学Rust | 框架篇 | Viz框架】轻量级 Web 框架——Viz

推荐整理分享【一起学Rust | 框架篇 | Viz框架】轻量级 Web 框架——Viz(rust 入门教程),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:rust一起玩的yy,rust+app,rust怎么一起玩,快速入门rust,rust 入门教程,rust一起玩的yy,rust tutorial,rust tutorial,内容如对您有帮助,希望把文章链接给更多的朋友!

文章目录前言特点一、Hello Viz1. 创建项目2. 引入viz3. 运行Hello Viz4. 运行结果注意二、Hello Viz代码详解导入组件处理请求主函数三、常见用法简单的处理程序实现处理程序特质路由传参链式组合程序中间件参数接收器路由一个简单的路由CRUD操作资源总结前言

Viz,是个基于RUst的,快速、健壮、灵活、轻量级的 Web 框架。

特点安全,禁止不安全代码轻量简单 + 灵活的处理器和中间件链式操作强大的Routing路由一、Hello Viz1. 创建项目

正如学习编程语言一样,我们先从官方入门案例学起,首先我们创建一个新项目

cargo new viz_hello

然后使用vscode打开

2. 引入viz

在Cargo.toml中写入,如下图

tokio = { version = "1.20.1", features = ["full"] }viz = "0.3.1"

然后使用build来下载依赖

cargo build

安装完成

3. 运行Hello Viz

复制以下代码到main.rs,

use std::net::SocketAddr;use viz::{Request, Result, Router, Server, ServiceMaker};async fn index(_: Request) -> Result<&'static str> { Ok("Hello Viz")}#[tokio::main]async fn main() -> Result<()> { let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); let app = Router::new().get("/", index); if let Err(err) = Server::bind(&addr) .serve(ServiceMaker::from(app)) .await { println!("{}", err); } Ok(())}4. 运行结果

如果你以上步骤没有出错,那么在终端中运行

cargo run

效果如下图 最后一行的意思是正在监听本地的127.0.0.1的3000端口,说明程序没有出错

此时在浏览器打开网址

http://localhost:3000/注意【一起学Rust | 框架篇 | Viz框架】轻量级 Web 框架——Viz(rust 入门教程)

localhost指向127.0.0.1

此时页面应该是这个样子的

二、Hello Viz代码详解

从整体上来看,这块代码主要分为3个部分,分别是导入组件,处理index请求和主程序

导入组件

首先导入了SocketAddr,用来表示socket地址,然后导入了Viz的一些组件

Request 请求Result 响应Router 路由Server 服务器ServiceMaker 服务

处理请求

这里使用异步函数来实现index的处理,传入Request,这个过程系统会自动为我们处理。然后响应的是字符串类型,在函数体中返回了字符串“Hello Viz”

主函数

在Viz中,主函数也是异步函数,使用addr表示本地地址和监听的端口,然后挂载Router,使与index处理器相联系,再开启服务器。

三、常见用法简单的处理程序async fn index(_: Request) -> Result<Response> { Ok(Response::text("Hello, World!"))}async fn about(_: Request) -> Result<&'static str> { Ok("About Me!")}async fn not_found(_: Request) -> Result<impl IntoResponse> { Ok("Not Found!")}实现处理程序特质#[derive(Clone)]struct MyHandler { code: Arc<AtomicUsize>,}#[async_trait]impl Handler<Request> for MyHandler { type Output = Result<Response>; async fn call(&self, req: Request) -> Self::Output { let path = req.path().clone(); let method = req.method().clone(); let code = self.code.fetch_add(1, Ordering::SeqCst); Ok(format!("code = {}, method = {}, path = {}", code, method, path).into_response()) }}路由传参

Viz 允许更灵活地组织代码。

async fn show_user(mut req: Request) -> Result<Response> { let Params(id) = req.extract::<Params<u64>>().await?; Ok(format!("post {}", id).into_response())}async fn show_user_ext(Params(id): Params<u64>) -> Result<impl IntoResponse> { Ok(format!("Hi, NO.{}", id))}async fn show_user_wrap(req: Request) -> Result<impl IntoResponse> { // https://github.com/rust-lang/rust/issues/48919 // show_user_ext.call(req).await FnExt::call(&show_user_ext, req).await}let app = Router::new() .get("/users/:id", show_user) .get("/users_wrap/:id", show_user_wrap) .get("/users_ext/:id", show_user_ext.into_handler());链式组合程序

HandlerExt是Handler的拓展特质,它提供了各种方便的组合函数。比如FutureExt和StreamExt特质。

async fn index(_: Request) -> Result<Response> { Ok(Response::text("hyper"))}async fn before(req: Request) -> Result<Request> { if req.method() == Method::POST { Ok(req) } else { Err(StatusCode::METHOD_NOT_ALLOWED.into_error()) }}async fn around<H>((req, handler): Next<Request, H>) -> Result<Response>where H: Handler<Request, Output = Result<Response>> + Clone,{ // before ... let result = handler.call(req).await; // after ... result}async fn after(result: Result<Response>) -> Result<Response> { result.map(|mut res| { *res.status_mut() = StatusCode::NO_CONTENT; res })}let routing = Router::new() .get("/", index.before(before).around(around).after(after));中间件

Viz 的中间件和处理程序具有共同的Handler特质,因此它很容易实现和扩展中间件。

我们可以将中间件添加到单个处理程序或所有处理程序。

我们还可以在构造过程中使用Transform特质 trait 来包装内部处理程序。

async fn index(_: Request) -> Result<Response> { Ok(StatusCode::OK.into_response())}async fn not_found(_: Request) -> Result<impl IntoResponse> { Ok(StatusCode::OK)}async fn show_user(Params(id): Params<u64>) -> Result<impl IntoResponse> { Ok(format!("post {}", id))}// middleware fnasync fn around<H>((req, handler): Next<Request, H>) -> Result<Response>where H: Handler<Request, Output = Result<Response>>,{ // before ... let result = handler.call(req).await; // after ... result}// middleware struct#[derive(Clone)]struct MyMiddleware {}#[async_trait]impl<H> Handler<Next<Request, H>> for MyMiddlewarewhere H: Handler<Request>,{ type Output = H::Output; async fn call(&self, (i, h): Next<Request, H>) -> Self::Output { h.call(i).await }}// A configuration for Timeout Middlewarestruct Timeout { delay: Duration,}impl Timeout { pub fn new(secs: u64) -> Self { Self { delay: Duration::from_secs(secs) } }}impl<H: Clone> Transform<H> for Timeout { type Output = TimeoutMiddleware<H>; fn transform(&self, h: H) -> Self::Output { TimeoutMiddleware(h, self.delay) }}// Timeout Middleware#[derive(Clone)]struct TimeoutMiddleware<H>(H, Duration);#[async_trait]impl<H> Handler<Request> for TimeoutMiddleware<H>where H: Handler<Request> + Clone,{ type Output = H::Output; async fn call(&self, req: Request) -> Self::Output { self.0.call(req).await }}let app = Router::new() .get("/", index // handler level .around(around) .around(MyMiddleware {}) .with(Timeout::new(1)) ) .route("/users/:id", get( show_user .into_handler() .map_into_response() // handler level .around(around) .with(Timeout::new(0)) ) .post( (|_| async { Ok(Response::text("update")) }) // handler level .around(around) .with(Timeout::new(0)) ) // route level .with_handler(MyMiddleware {}) .with(Timeout::new(2)) ) .get("/*", not_found .map_into_response() // handler level .around(around) .around(MyMiddleware {}) ) // router level .with_handler(around) .with_handler(MyMiddleware {}) .with(Timeout::new(4));参数接收器

从Request中提取参数。

struct Counter(u16);#[async_trait]impl FromRequest for Counter { type Error = Infallible; async fn extract(req: &mut Request) -> Result<Self, Self::Error> { let c = get_query_param(req.query_string()); Ok(Counter(c)) }}fn get_query_param(query: Option<&str>) -> u16 { let query = query.unwrap_or(""); let q = if let Some(pos) = query.find('q') { query.split_at(pos + 2).1.parse().unwrap_or(1) } else { 1 }; cmp::min(500, cmp::max(1, q))}路由

识别URL和分配处理器。

一个简单的路由async fn index(_: Request) -> Result<Response> { Ok(().into_response())}let root = Router::new() .get("/", index) .route("/about", get(|_| async { Ok("about") }));let search = Router::new() .route("/", Route::new().get(|_| async { Ok("search") }));CRUD操作

添加带请求方式的方法。

async fn index_todos(_: Request) -> Result<impl IntoResponse> { Ok(())}async fn create_todo(_: Request) -> Result<&'static str> { Ok("created")}async fn new_todo(_: Request) -> Result<Response> { Ok(Response::html(r#" <form method="post" action="/"> <input name="todo" /> <button type="submit">Create</button> </form> "#))}async fn show_todo(mut req: Request) -> Result<Response> { let Params(id): Params<u64> = req.extract().await?; Ok(Response::text(format!("todo's id is {}", id)))}async fn update_todo(_: Request) -> Result<()> { Ok(())}async fn destroy_todo(_: Request) -> Result<()> { Ok(())}async fn edit_todo(_: Request) -> Result<()> { Ok(())}let todos = Router::new() .route("/", get(index_todos).post(create_todo)) .post("/new", new_todo) .route("/:id", get(show_todo).patch(update_todo).delete(destroy_todo)) .get("/:id/edit", edit_todo);资源// GET `/search`async fn search_users(_: Request) -> Result<Response> { Ok(Response::json::<Vec<u64>>(vec![])?)}// GET `/`async fn index_users(_: Request) -> Result<Response> { Ok(Response::json::<Vec<u64>>(vec![])?)}// GET `/new`async fn new_user(_: Request) -> Result<&'static str> { Ok("User Form")}// POST `/`async fn create_user(_: Request) -> Result<&'static str> { Ok("Created User")}// GET `/user_id`async fn show_user(_: Request) -> Result<&'static str> { Ok("User ID 007")}// GET `/user_id/edit`async fn edit_user(_: Request) -> Result<&'static str> { Ok("Edit User Form")}// PUT `/user_id`async fn update_user(_: Request) -> Result<&'static str> { Ok("Updated User")}// DELETE `/user_id`async fn delete_user(_: Request) -> Result<&'static str> { Ok("Deleted User")}let users = Resources::default() .named("user") .route("/search", get(search_users)) .index(index_users) .new(new_user) .create(create_user) .show(show_user) .edit(edit_user) .update(update_user) .destroy(delete_user);总结

本期主要是对Rust的轻量级Web框架Viz进行了入门级的了解,并且给出了Viz官方的示例代码,包括中间件,响应处理,路由等组件的用法,可以看出Viz是个纯web框架,非常的简洁。在后续的文章中,将会陆续为大家介绍rust的数据库操作,json操作等相关技术,rust做web后端的相关技术补齐就开始项目实战。如果你对rust感兴趣,请关注本系列文章。

本文链接地址:https://www.jiuchutong.com/zhishi/300621.html 转载请保留说明!

上一篇:js-cookie的使用(js-cookie vue)

下一篇:YOLOv5|YOLOv7|YOLOv8改各种IoU损失函数:YOLOv8涨点Trick,改进添加SIoU损失函数、EIoU损失函数、GIoU损失函数、α-IoU损失函数

  • 土地税税额标准
  • 销售不动产税率9%还是5%
  • 电子承兑转出后银行有凭证吗
  • 土地款发票是否可以抵扣
  • 开立一般户需要基本户开户行许可证吗
  • 子公司分红母公司要不要交税
  • 收到投资款如何写凭证
  • 折扣金额发票
  • 装饰行业可否用石灰代替
  • 折旧完的固定资产出售
  • 银行贷款损失的认定标准
  • 农业企业土地租金会计分录
  • 企业计提福利费时,贷记应付职工薪酬
  • 营改增的主要内容
  • 资产减值损失和信用损失的区别
  • 柴油可以销售吗
  • 对方已经认证的发票怎么作废
  • 取得特许权使用费收入增值税税率
  • 个人所得税减半征收
  • 减免税款余额方法有哪些
  • 开专票需要哪些东西
  • 耕地占用税与土地出让金
  • 代扣代缴境外增值税可以抵扣
  • 增值税专用发票怎么开
  • 贴现利息会计处理
  • 各类基本社会保障性缴款是单位缴纳部分吗
  • 应收账款和预收账款的关系
  • 广告制作包括印花吗
  • 支付给代理机构的手续费
  • pavkre.exe - pavkre是什么进程 作用是什么
  • php中序遍历
  • 直接材料成本差异账户在平时登记贷方登记
  • 酒店装修期间的费用如何核算
  • 员工旅游的费用可以税前扣除吗
  • python模块怎么写
  • 发票抵扣联能报销吗
  • vue的mvvm模型
  • 前端从后端拿excel文件
  • 跟踪数据包命令
  • netconf over ssh
  • 企业年产值与年收入比例
  • 现金和现金等价物包括哪些
  • 固定资产记到什么账本
  • 合伙企业退伙如何缴纳个人所得税
  • discuz发帖标签
  • 建筑业用的会计账簿
  • 六税一费和六税两费的区别
  • 企业年金的功能代理人
  • db2 select as
  • 其他综合收益影响留存收益吗
  • sql服务器无法启动的解决
  • 融资租赁固定资产折旧年限
  • 冲销暂估入账用什么凭证
  • 免税收入就是不征收收入,均属于税收优惠范畴
  • 有限合伙企业的
  • 异地建筑服务开全电发票
  • 每月增值税怎么做账
  • 购买办公楼分期合同
  • 银行日记账记错了怎么办
  • 购销合同交的印花税税率
  • 个人出租租房收什么税
  • 应收帐款坏账处理
  • 如何控制自己不磨牙
  • ubuntu系统防火墙状态
  • windows系统中巧用系统中的文件查看有谁用过我们的电脑 查看方法介绍
  • win10无法uefi
  • ubuntu20.04.1安装
  • win10开机黑屏进入不了系统界面
  • win8.1隐藏文件夹
  • linux的安装教程
  • dos 浏览器
  • html头像代码
  • jquery easyui validatebox remote的使用详解
  • jquery的validate前端表单验证
  • jQuery+ajax+asp.net获取Json值的方法
  • 重庆电子税务局网页版登录
  • 河北税务云办税厅官方
  • 准予扣除外购的应税消费品已纳消费税税款的是
  • 宝鸡二套房契税多少
  • 天津摇号申请查询
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设