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

重庆 机械有限公司 江北网站建设百度空间登录入口

重庆 机械有限公司 江北网站建设,百度空间登录入口,客户引流的最快方法是什么,wordpress设置略缩图外链图片Actix-web 学习 请求处理分为两个阶段。 首先调用处理程序对象,返回实现Responder trait的任何对象。 然后,在返回的对象上调用respond_to(),将其自身转换为AsyncResult或Error。 默认情况下,actix为一些标准类型提供响应器实现&…

Actix-web 学习

请求处理分为两个阶段。
首先调用处理程序对象,返回实现Responder trait的任何对象。
然后,在返回的对象上调用respond_to(),将其自身转换为AsyncResult或Error。
默认情况下,actix为一些标准类型提供响应器实现,比如静态str、字符串等。要查看完整的实现列表,请查看响应器文档。

基础的Demo

extern crate actix_web;
extern crate futures;use actix_web::{server, App, HttpRequest, Responder, HttpResponse, Body};
use std::cell::Cell;
use std::io::Error;
use futures::future::{Future, result};
use futures::stream::once;
use bytes::Bytes;struct AppState {counter: Cell<usize>,
}// 有状态
fn index2(req: &HttpRequest<AppState>) -> String {let count = req.state().counter.get() + 1; // <- get countreq.state().counter.set(count); // <- store new count in stateformat!("Request number: {}", count) // <- response with count
}// 静态文本
fn index1(_req: &HttpRequest) -> impl Responder {"Hello world!"
}fn index11(_req: &HttpRequest) -> &'static str {"Hello world!"
}// 异步内容
fn index12(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {result(Ok(HttpResponse::Ok().content_type("text/html").body(format!("Hello!")))).responder()
}fn index13(req: &HttpRequest) -> Box<Future<Item=&'static str, Error=Error>> {result(Ok("Welcome!")).responder()
}fn index14(req: &HttpRequest) -> HttpResponse {let body = once(Ok(Bytes::from_static(b"test")));HttpResponse::Ok().content_type("application/json").body(Body::Streaming(Box::new(body)))
}// 文件
// fn f1(req: &HttpRequest) -> io::Result<fs::NamedFile> {
//     Ok(fs::NamedFile::open("static/index.html")?)
// }fn main() {let addr = "0.0.0.0:8888";let s = server::new(|| {vec![App::new().prefix("/app1").resource("/", |r| r.f(index1)).resource("/2", |r| r.f(index11)).resource("/3", |r| r.f(index12)).resource("/4", |r| r.f(index13)).resource("/5", |r| r.f(index14)).boxed(),App::with_state(AppState { counter: Cell::new(0) }).prefix("/app2").resource("/", |r| r.f(index2)).boxed(),]}).bind(addr).unwrap();println!("server run: {}", addr);s.run();
}

请求内容解析

extern crate actix_web;
extern crate futures;
#[macro_use]
extern crate serde_derive;use actix_web::*;
use std::cell::Cell;
use std::io::Error;
use futures::future::{Future, result};
use futures::stream::once;
use bytes::Bytes;// url 解析
#[derive(Debug, Serialize, Deserialize)]
struct Info {userid: u32,friend: String,
}fn index(info: Path<Info>) -> String {format!("Welcome {}!", info.friend)
}fn index2(info: Path<(u32, String)>) -> Result<String> {Ok(format!("Welcome {}! {}", info.1, info.0))
}// url 参数解析
fn index3(info: Query<Info>) -> String {format!("Welcome {} {}", info.userid, info.friend)
}// body json 解析
fn index4(info: Json<Info>) -> Result<String> {Ok(format!("Welcome {} {}", info.userid, info.friend))
}// body form 解析
fn index5(form: Form<Info>) -> Result<String> {Ok(format!("Welcome {}!", form.userid))
}// json 手动解析1
fn index6(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {req.json().from_err().and_then(|val: Info| {println!("model: {:?}", val);Ok(HttpResponse::Ok().json(val))  // <- send response}).responder()
}// Json手动解析2, 手动处理body
fn index7(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {// `concat2` will asynchronously read each chunk of the request body and// return a single, concatenated, chunkreq.concat2()// `Future::from_err` acts like `?` in that it coerces the error type from// the future into the final error type.from_err()// `Future::and_then` can be used to merge an asynchronous workflow with a// synchronous workflow.and_then(|body| {let obj = serde_json::from_slice::<Info>(&body)?;Ok(HttpResponse::Ok().json(obj))}).responder()
}// multipart
//fn index8(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {get multipart and iterate over multipart items
//    req.multipart()
//        .and_then(|item| {
//            match item {
//                multipart::MultipartItem::Field(field) => {
//                    println!("==== FIELD ==== {:?} {:?}",
//                             field.headers(),
//                             field.content_type());
//                    Either::A(
//                        field.map(|chunk| {
//                            println!("-- CHUNK: \n{}",
//                                     std::str::from_utf8(&chunk).unwrap());
//                        })
//                            .fold((), |_, _| result(Ok(()))))
//                }
//                multipart::MultipartItem::Nested(mp) => {
//                    Either::B(result(Ok(())))
//                }
//            }
//        })
//        ...
//    // https://github.com/actix/examples/tree/master/multipart/
//}// stream
//fn index9(req: &HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
//    req
//        .payload()
//        .from_err()
//        .fold((), |_, chunk| {
//            println!("Chunk: {:?}", chunk);
//            result::<_, error::PayloadError>(Ok(()))
//        })
//        .map(|_| HttpResponse::Ok().finish())
//        .responder()
//}// 通用解析
// fn index(req: &HttpRequest) -> HttpResponse {
// 	let params = Path::<(String, String)>::extract(req);
// 	let info = Json::<MyInfo>::extract(req); // 	...
// }fn main() {let addr = "0.0.0.0:8888";let s = server::new(|| {vec![App::new().prefix("/args").resource("/1/{userid}/{friend}", |r| r.method(http::Method::GET).with(index)).resource("/2/{userid}/{friend}", |r| r.with(index2)).route("/3", http::Method::GET, index3).route("/4", http::Method::POST, index4).route("/5", http::Method::POST, index5).boxed(),]}).bind(addr).unwrap();println!("server run: {}", addr);s.run();
}

Static

extern crate actix_web;use actix_web::{App};
use actix_web::fs::{StaticFileConfig, StaticFiles};#[derive(Default)]
struct MyConfig;impl StaticFileConfig for MyConfig {fn is_use_etag() -> bool {false}fn is_use_last_modifier() -> bool {false}
}fn main() {App::new().handler("/static",StaticFiles::with_config(".", MyConfig).unwrap().show_files_listing()).finish();
}

Websocket

use actix::*;
use actix_web::*;/// Define http actor
struct Ws;impl Actor for Ws {type Context = ws::WebsocketContext<Self>;
}/// Handler for ws::Message message
impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {match msg {ws::Message::Ping(msg) => ctx.pong(&msg),ws::Message::Text(text) => ctx.text(text),ws::Message::Binary(bin) => ctx.binary(bin),_ => (),}}
}fn main() {App::new().resource("/ws/", |r| r.f(|req| ws::start(req, Ws))).finish();
}

middleware

用到了再说
https://actix.rs/docs/middleware/

http://www.zhongyajixie.com/news/63632.html

相关文章:

  • 郑州动力无限网站建设郑州百度seo关键词
  • flash源文件网站网络营销是做什么
  • 目前旅游网站开发百度指数的需求指数
  • 中石化第十建设公司官网seo诊断方法步骤
  • 哪个网站做黄金交易最好seo赚钱
  • 本地电脑做服务器 建网站seo简单优化操作步骤
  • 网站建设wordpress比较百度新闻头条
  • 如何搭建个人网站怎么在百度上推广自己
  • 免费1级做爰片在线观看网站黄页引流推广链接
  • wordpress301台州网站优化公司
  • 做博彩网站代理犯法吗2021年热门关键词
  • 交友网站开发功能需求东莞头条最新新闻
  • 什么网站可以找人做设计师网站推广优化的公司
  • 无锡低价网站排名百度客服电话人工服务热线电话
  • 网站建设主流编程软件今日热搜榜前十名
  • html5做网站导航腾讯广告推广平台
  • 免费的设计网站有哪些网站流量
  • 网站设计开发团队网站搜索引擎优化方案
  • 网站使用功能介绍是用什么软件做的福鼎网站优化公司
  • 济南手机网站百度指数移动版app
  • 美食分享网站怎么做免费百度下载
  • 做美容美发的网站有哪些宁波seo推广公司排名
  • 朝阳区手机网站制作服务网站备案查询官网
  • 做一款推荐类的网站昆明seocn整站优化
  • 柬埔寨网站开发互联网营销是什么
  • 网站排名突然下降上海优化公司有哪些
  • 郴州网站制作公司网站媒体推广方案
  • 找装修公司网站中国营销网官网
  • 自己公司的网站怎么编辑器app关键词优化
  • 青岛开发区制作网站公司整合营销名词解释