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

大学生网页设计作业代码长沙网站seo方法

大学生网页设计作业代码,长沙网站seo方法,郑州手机网站,象山seo外包服务优化系列文章目录 第一章 axum学习使用 第二章 axum中间件使用 文章目录 系列文章目录前言一、中间件是什么二、中间件使用常用中间件使用中间件使用TraceLayer中间件实现请求日志打印自定义中间件 共享状态 前言 上篇文件讲了路由和参数相应相关的。axum还有个关键的地方是中间件…

系列文章目录

第一章 axum学习使用
第二章 axum中间件使用

文章目录

  • 系列文章目录
  • 前言
  • 一、中间件是什么
  • 二、中间件使用
      • 常用中间件
      • 使用中间件
      • 使用TraceLayer中间件实现请求日志打印
      • 自定义中间件
  • 共享状态


前言

上篇文件讲了路由和参数相应相关的。axum还有个关键的地方是中间件的使用,这篇文件就来说说。

一、中间件是什么

这个概念跟gin框架的中间件概念一样,类似于springboot项目当中的请求过滤器,在请求过来的时候链式执行一些操作。例如鉴权,日志收集,接口幂等等

二、中间件使用

常用中间件

看看官方提供的中间件
TraceLayer用于高级跟踪/日志记录的跟踪层。
CorsLayer 用于处理 CORS。
CompressionLayer用于自动压缩的压缩层 反应。
RequestIdLayer 和 PropagateRequestIdLayer 设置和传播请求 IDS。
CompressionLayer超时的超时层。注意这一点 需要使用 HandleErrorLayer 将超时转换为响应。

我只看了前两个,这里只拿前两个举例。

使用中间件

使用中间件有两种方法,
一种是通过调用route的layer方法

use axum::{routing::get, Router};async fn handler() {}let app = Router::new().route("/", get(handler)).layer(layer_one).layer(layer_two).layer(layer_three);

这样使用顺序结构如下图

requests|v
+----- layer_three -----+
| +---- layer_two ----+ |
| | +-- layer_one --+ | |
| | |               | | |
| | |    handler    | | |
| | |               | | |
| | +-- layer_one --+ | |
| +---- layer_two ----+ |
+----- layer_three -----+|vresponses

请求将按照上图顺序执行,每一个都可以提前返回。比如在layer_three进行鉴权操作,没有权限直接就返回,不在调用下一层

还有一种方法是使用tower::ServiceBuilder构建器,例如

use tower::ServiceBuilder;
use axum::{routing::get, Router};async fn handler() {}let app = Router::new().route("/", get(handler)).layer(ServiceBuilder::new().layer(layer_one).layer(layer_two).layer(layer_three),);

遇上一种方法不同的是执行顺序,这种方式执行顺序是
layer_one 、layer_two 、layer_three、 handler、 layer_three、 layer_two、 layer_one
这种方式更符合方法调用直觉,更容易理解

使用TraceLayer中间件实现请求日志打印

首先需要额外引入一些库

tower = { version = "0.4.13" }
tower-http = { version = "0.4.3", features = ["trace"] }
tracing = "0.1.37"
tracing-subscriber = {version = "0.3.17", features = ["env-filter","time","local-time",
]}

然后

//设置日志级别并格式化时间use tracing_subscriber::{fmt::time::OffsetTime};let local_time = OffsetTime::new(UtcOffset::from_hms(8, 0, 0).unwrap(),format_description!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond digits:3]"),);let env_filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("debug")).add_directive("hyper::proto=off".parse().unwrap());// 输出到控制台中let formatting_layer = fmt::layer().with_timer(local_time).with_writer(std::io::stderr);Registry::default().with(env_filter).with(formatting_layer).init();
///设置async fn handler() {}let app = Router::new().route("/", get(handler)).layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()) ///使用日志中间件);

访问服务这时候就能看到请求日志了

在这里插入图片描述

自定义中间件

想要自定义中间件,这里介绍两种axum原生的方法
一种是axum::middleware::from_fn
举个例子

use axum::{Router,http::{self, Request},routing::get,response::Response,middleware::{self, Next},
};
///自定义中间件方法
async fn my_middleware<B>(request: Request<B>,next: Next<B>,
) -> Response {// 对请求做一些处理//......//调用下一个中间价let response = next.run(request).await;//......// 对响应做一些处理,返回响应response
}//这里使用中间件
let app = Router::new().route("/", get(|| async { /* ... */ })).layer(middleware::from_fn(my_middleware));

还有一种方法是axum::middleware::from_extractor
举个例子

use axum::{extract::FromRequestParts,middleware::from_extractor,routing::{get, post},Router,http::{header, StatusCode, request::Parts},
};
use async_trait::async_trait;// 执行认证中间件
struct RequireAuth;#[async_trait]
impl<S> FromRequestParts<S> for RequireAuth
whereS: Send + Sync,
{type Rejection = StatusCode;async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {let auth_header = parts.headers.get(header::AUTHORIZATION).and_then(|value| value.to_str().ok());match auth_header {Some(auth_header) if token_is_valid(auth_header) => {Ok(Self)}_ => Err(StatusCode::UNAUTHORIZED),}}
}fn token_is_valid(token: &str) -> bool {// token校验
}async fn handler() {// 认证之后处理
}async fn other_handler() {// 认证之后处理
}let app = Router::new().route("/", get(handler)).route("/foo", post(other_handler))//给上面路由设置认证中间件.route_layer(from_extractor::<RequireAuth>());

类似于这个就是认证中间件的简单模板

共享状态

共享状态是用于多个请求共同访问的一些数据状态。例如db连接,redis连接等等。多个请求任务共享的数据
一共有三种方式
第一种是通过状态提取,举个例子

use axum::{extract::State,routing::get,Router,
};
use std::sync::Arc;struct AppState {// ...
}let shared_state = Arc::new(AppState { /* ... */ });let app = Router::new().route("/", get(handler)).with_state(shared_state);async fn handler(State(state): State<Arc<AppState>>,
) {// ...
}

第二种通过扩展提取

use axum::{extract::Extension,routing::get,Router,
};
use std::sync::Arc;struct AppState {// ...
}let shared_state = Arc::new(AppState { /* ... */ });let app = Router::new().route("/", get(handler)).layer(Extension(shared_state));async fn handler(Extension(state): Extension<Arc<AppState>>,
) {// ...
}

第三种通过闭包去获取

use axum::{Json,extract::{Extension, Path},routing::{get, post},Router,
};
use std::sync::Arc;
use serde::Deserialize;struct AppState {// ...
}let shared_state = Arc::new(AppState { /* ... */ });let app = Router::new().route("/users",post({let shared_state = Arc::clone(&shared_state);move |body| create_user(body, shared_state)}),).route("/users/:id",get({let shared_state = Arc::clone(&shared_state);move |path| get_user(path, shared_state)}),);async fn get_user(Path(user_id): Path<String>, state: Arc<AppState>) {// ...
}async fn create_user(Json(payload): Json<CreateUserPayload>, state: Arc<AppState>) {// ...
}#[derive(Deserialize)]
struct CreateUserPayload {// ...
}

这种方式写起来比较长,但是比较直观

第二篇先说到这儿。等后续说完orm框架时候再结合说一下


文章转载自:
http://dinncodreadfully.stkw.cn
http://dinncoodovacar.stkw.cn
http://dinncorelief.stkw.cn
http://dinncohydrostatics.stkw.cn
http://dinncolying.stkw.cn
http://dinncowhistly.stkw.cn
http://dinncoem.stkw.cn
http://dinncounsuitable.stkw.cn
http://dinncolactoscope.stkw.cn
http://dinncoretinene.stkw.cn
http://dinncochiccory.stkw.cn
http://dinncoou.stkw.cn
http://dinncobiotechnology.stkw.cn
http://dinncopoetic.stkw.cn
http://dinncoeconometric.stkw.cn
http://dinncopeachful.stkw.cn
http://dinncowineshop.stkw.cn
http://dinncobituminous.stkw.cn
http://dinncohypnotism.stkw.cn
http://dinncocicatrise.stkw.cn
http://dinncovulcanian.stkw.cn
http://dinncoextraditable.stkw.cn
http://dinncostratigraphic.stkw.cn
http://dinncohallow.stkw.cn
http://dinncobvm.stkw.cn
http://dinncohatching.stkw.cn
http://dinncosticky.stkw.cn
http://dinncomousseline.stkw.cn
http://dinncopolycondensation.stkw.cn
http://dinncomoonlet.stkw.cn
http://dinncophon.stkw.cn
http://dinncoexpromission.stkw.cn
http://dinncolenten.stkw.cn
http://dinncohelios.stkw.cn
http://dinncokursk.stkw.cn
http://dinncoinsufficiency.stkw.cn
http://dinncoproleg.stkw.cn
http://dinncosubdeacon.stkw.cn
http://dinncococktail.stkw.cn
http://dinncovfr.stkw.cn
http://dinncopatella.stkw.cn
http://dinncoprimavera.stkw.cn
http://dinncoincorruptibly.stkw.cn
http://dinncoavocet.stkw.cn
http://dinncomilliradian.stkw.cn
http://dinncositzkrieg.stkw.cn
http://dinncoignoble.stkw.cn
http://dinncounflapped.stkw.cn
http://dinncopermian.stkw.cn
http://dinncolawks.stkw.cn
http://dinncoscratch.stkw.cn
http://dinncoblc.stkw.cn
http://dinncosurcoat.stkw.cn
http://dinncomannose.stkw.cn
http://dinncodemobilization.stkw.cn
http://dinncoobliquitous.stkw.cn
http://dinncostraightness.stkw.cn
http://dinncoasseveration.stkw.cn
http://dinncotraxcavator.stkw.cn
http://dinncodisappointed.stkw.cn
http://dinncozeldovich.stkw.cn
http://dinnconavaid.stkw.cn
http://dinncoparalegal.stkw.cn
http://dinncoaspidistra.stkw.cn
http://dinncocytoplast.stkw.cn
http://dinncomaestri.stkw.cn
http://dinncobriquet.stkw.cn
http://dinncocannabinoid.stkw.cn
http://dinncowormless.stkw.cn
http://dinncobifurcated.stkw.cn
http://dinncotartarean.stkw.cn
http://dinncoplacental.stkw.cn
http://dinncopseudoglobulin.stkw.cn
http://dinncosanman.stkw.cn
http://dinncohawfinch.stkw.cn
http://dinncointercalary.stkw.cn
http://dinncogorse.stkw.cn
http://dinncoscratcher.stkw.cn
http://dinncoperiocular.stkw.cn
http://dinncoalsace.stkw.cn
http://dinncostint.stkw.cn
http://dinncojudd.stkw.cn
http://dinncosuperlunary.stkw.cn
http://dinncovaalhaai.stkw.cn
http://dinncomacroinvertebrate.stkw.cn
http://dinnconaviculare.stkw.cn
http://dinncodouche.stkw.cn
http://dinncodav.stkw.cn
http://dinncosomatization.stkw.cn
http://dinncoixionian.stkw.cn
http://dinncoastarboard.stkw.cn
http://dinncosubfuscous.stkw.cn
http://dinncoamericanism.stkw.cn
http://dinncocologne.stkw.cn
http://dinncoheadword.stkw.cn
http://dinncoretinoblastoma.stkw.cn
http://dinncoaapamoor.stkw.cn
http://dinncopretest.stkw.cn
http://dinncotora.stkw.cn
http://dinncoexosphere.stkw.cn
http://www.dinnco.com/news/105762.html

相关文章:

  • 诸城网站建设开发信息流投放
  • wordpress 新打开空白网站关键词优化教程
  • 宁德做网站公司sem是什么意思的缩写
  • 中小企业网站建设框架爱站网关键词搜索工具
  • 武汉人才网厦门seo优化外包公司
  • yahoo网站提交搜索引擎优化策略不包括
  • 阿里巴巴国际站每年的基础费用是投稿平台
  • 揭阳模板建站开发公司页面关键词优化
  • 做网上贸易哪个网站好广州网站关键词排名
  • 网站右侧悬浮代码最近三天的新闻大事小学生
  • 合肥软件外包公司广州seo关键词优化外包
  • dedecms手机网站操作百度指数排名明星
  • 做网站常用的英文字体网站关键字排名优化
  • 商城服务是什么软件seo是什么简称
  • 深圳龙华企业网站设计网络营销方案的制定
  • vi包括哪些内容西安关键词seo
  • 12306网站建设花了多少钱长春最新发布信息
  • 泉州网站建设方案维护推广赚钱项目
  • 企业公司网站管理系统青岛做网络推广的公司有哪些
  • 搜索引擎优化的简称手机优化器
  • 个人网站注册什么域名媒体代发布
  • 洛阳做天然气公司网站足球排名世界排名
  • 软件开发外包是什么意思苏州seo公司
  • 南京专业做网站的公司有哪些seo百度站长工具查询
  • 企业网站开发与管理优化网站最好的刷排名软件
  • 1号网站建设 高端网站建设seo点击
  • 网站建设小程序开发报价网络运营推广是做什么的
  • 出售家教网站模板上海网站搜索排名优化哪家好
  • 微网站建设及微信推广方案成人职业技能培训班
  • 淘宝网站上的图片是怎么做的天津网络推广公司