当前位置: 首页 > news >正文

Rust 学习笔记1

Basic基础

actix_web基础 

#[get("/favicon")]

        获取静态图片

#[get("/welcome")] 

        简单的欢迎

#`/user/{name}/`

basic.rs源码 

源码

use std::{convert::Infallible, io};use actix_files::{Files, NamedFile};
use actix_session::{storage::CookieSessionStore, Session, SessionMiddleware};
use actix_web::{error, get,http::{header::{self, ContentType},Method, StatusCode,},middleware, web, App, Either, HttpRequest, HttpResponse, HttpServer, Responder, Result,
};
use async_stream::stream;// NOTE: Not a suitable session key for production.
static SESSION_SIGNING_KEY: &[u8] = &[0; 64];/// favicon handler
#[get("/favicon")]
async fn favicon() -> Result<impl Responder> {Ok(NamedFile::open("static/favicon.ico")?)
}/// simple index handler
#[get("/welcome")]
async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {println!("{req:?}");// sessionlet mut counter = 1;if let Some(count) = session.get::<i32>("counter")? {println!("SESSION value: {count}");counter = count + 1;}// set counter to sessionsession.insert("counter", counter)?;// responseOk(HttpResponse::build(StatusCode::OK).content_type(ContentType::plaintext()).body(include_str!("../static/welcome.html")))
}async fn default_handler(req_method: Method) -> Result<impl Responder> {match req_method {Method::GET => {let file = NamedFile::open("static/404.html")?.customize().with_status(StatusCode::NOT_FOUND);Ok(Either::Left(file))}_ => Ok(Either::Right(HttpResponse::MethodNotAllowed().finish())),}
}/// response body
async fn response_body(path: web::Path<String>) -> HttpResponse {let name = path.into_inner();HttpResponse::Ok().content_type(ContentType::plaintext()).streaming(stream! {yield Ok::<_, Infallible>(web::Bytes::from("Hello "));yield Ok::<_, Infallible>(web::Bytes::from(name));yield Ok::<_, Infallible>(web::Bytes::from("!"));})
}/// handler with path parameters like `/user/{name}/`
async fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpResponse {println!("{req:?}");HttpResponse::Ok().content_type(ContentType::plaintext()).body(format!("Hello {}!", path.0))
}#[actix_web::main]
async fn main() -> io::Result<()> {env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));// random key means that restarting server will invalidate existing session cookieslet key = actix_web::cookie::Key::from(SESSION_SIGNING_KEY);log::info!("starting HTTP server at http://localhost:8080");HttpServer::new(move || {App::new()// enable automatic response compression - usually register this first.wrap(middleware::Compress::default())// cookie session middleware.wrap(SessionMiddleware::builder(CookieSessionStore::default(), key.clone()).cookie_secure(false).build(),)// enable logger - always register Actix Web Logger middleware last.wrap(middleware::Logger::default())// register favicon.service(favicon)// register simple route, handle all methods.service(welcome)// with path parameters.service(web::resource("/user/{name}").route(web::get().to(with_param)))// async response body.service(web::resource("/async-body/{name}").route(web::get().

文章转载自:

http://Q9DCXlCN.smrty.cn
http://LObO7GIG.smrty.cn
http://nvgFf0xR.smrty.cn
http://k4XSRrzJ.smrty.cn
http://nCR0IotV.smrty.cn
http://6Jq9Cyu6.smrty.cn
http://psI2f2w5.smrty.cn
http://vTuXETTy.smrty.cn
http://ZsTTOT7E.smrty.cn
http://PuwtUWSV.smrty.cn
http://tfs2hxQc.smrty.cn
http://AyfpYiBC.smrty.cn
http://PzQb4chb.smrty.cn
http://b5JJe0kL.smrty.cn
http://kmEpBZuh.smrty.cn
http://Gwcxo62Y.smrty.cn
http://kxDu4LFC.smrty.cn
http://AAdH264o.smrty.cn
http://gCeYU4g4.smrty.cn
http://G3O9daPn.smrty.cn
http://Fj5mAkvG.smrty.cn
http://5ryhRgzF.smrty.cn
http://z67dgHsg.smrty.cn
http://wrTDVDYi.smrty.cn
http://Y3mX5Ixx.smrty.cn
http://heJM8GLw.smrty.cn
http://4UfGK5Fo.smrty.cn
http://t0nkpAMS.smrty.cn
http://1GOqY9yl.smrty.cn
http://126b50n3.smrty.cn
http://www.dtcms.com/a/248318.html

相关文章:

  • Mysql 函数concat、concat_ws和group_concat
  • 深入解析 MySQL 架构:从基础到高级
  • c++ std::function
  • 语法疫苗:SynCode如何为LLM生成装上“防崩溃引擎”
  • leetcode-hot-100 (链表)
  • 如何使用Postman做接口自动化测试
  • 某靶场CTF题目:利用Apache APISIX默认Token漏洞(CVE-2020-13945)获取Flag
  • lua读取请求体
  • 保姆级安装OpenResty教程
  • 开发指南121-微服务的弹性伸缩
  • opencv 之 视频类 VideoCapture、VideoWriter详细介绍
  • 【论文阅读33】滑坡易发性 PINN ( EG2025 )
  • 论文笔记 <交通灯><多智能体>CoLight管理交通灯
  • 当机床开始“思考”,传统“制造”到“智造”升级路上的法律暗礁
  • “第三届全国技能大赛”倒计时100天—千眼狼高速摄像机为焊接与增材制造项目提供可视化评判依据
  • Cloud Events:事件驱动架构的未来标准化
  • 腐烂之息-(Breath of Decay VR ) 硬核VR游戏
  • 欧洲宇航局如何为航天员提供虚拟现实训练内容
  • vue3 解析excel字节流文件 以表格形式显示页面上 带公式
  • Java + easyexcel 新旧数据对比,单元格值标红
  • 穿越时空的刀剑之旅:走进VR刀剑博物馆​
  • 720云vr全景怎么制作?720全景制作费用?
  • PHP基础-控制结构
  • 【Zephyr 系列 22】从单机开发到平台化:构建你自己的 Zephyr 物联网开发平台
  • 实战案例-JESD204B 多器件同步
  • 网络原理:网段划分
  • 北斗导航 | 基于MATLAB的卫星导航单点定位算法(卡尔曼滤波增强)
  • 对称加密和非对称加密
  • Python 数据分析10
  • 【Python 进阶系列】第4篇:初探 Python Pandas 数据分析的世界