我知道 Axum 是建立在 Tokio 之上的,并且 Tokio 有一个多线程调度程序和当前线程调度程序。
是否可以设置运行时以使其在单线程中服务请求?
fetch在发送a 之前,浏览器将发送一个请求方法OPTIONS来确认 API 将接受来自特定来源的脚本的请求。
Chrome 显示我的 Axum 服务器正在拒绝我客户端的 405 请求。我的路由器如下所示:
\nlet app = Router::new()\n .layer(TraceLayer::new_for_http())\n .layer(CorsLayer::permissive())\n .route("/api", post(server));\nRun Code Online (Sandbox Code Playgroud)\nRouter::layer表示所有到router的请求都会被layer\xe2\x80\x99s对应的中间件处理。但我不确定它是否发挥了作用。
\n我使用 Axum 框架构建一个简单的休息服务器。我想要一种“应用程序状态”,其中包含一些可重用的组件,供我的一些处理程序重用/使用。
#![allow(incomplete_features)]
#![feature(async_fn_in_trait)]
use axum::{routing::post, Router};
use std::{net::SocketAddr, sync::Arc};
mod modules;
use modules::auth::handlers::login;
pub struct AppState<'a> {
user_credentials_repository: UserCredentialsRepository<'a>,
}
pub struct UserCredentialsRepository<'a> {
shared_name: &'a mut String,
}
impl<'a> UserCredentialsRepository<'a> {
pub fn new(shared_name: &'a mut String) -> UserCredentialsRepository<'a> {
UserCredentialsRepository { shared_name }
}
}
#[tokio::main]
async fn main() {
let mut name = String::from("Tom");
let mut user_credentials_repository = UserCredentialsRepository::new(&mut name);
let shared_state = Arc::new(AppState {
user_credentials_repository,
});
let app = Router::new()
.route("/login", post(login))
.with_state(shared_state);
let …Run Code Online (Sandbox Code Playgroud) 我认为应该为返回 a 的函数Handler实现:asyncStatusCode
use axum::{
headers,
http::StatusCode,
routing::{delete, get, post, put},
Router,
};
pub fn create_routes() -> Router {
Router::new().route("/webhook", post(webhook_handler()))
}
#[debug_handler]
async fn webhook_handler() -> StatusCode {
StatusCode::OK
}
Run Code Online (Sandbox Code Playgroud)
use axum::{
headers,
http::StatusCode,
routing::{delete, get, post, put},
Router,
};
pub fn create_routes() -> Router {
Router::new().route("/webhook", post(webhook_handler()))
}
#[debug_handler]
async fn webhook_handler() -> StatusCode {
StatusCode::OK
}
Run Code Online (Sandbox Code Playgroud)
这看起来与文档中提供的示例几乎相同:
// `StatusCode` gives an empty response with that status code
async fn status() -> StatusCode …Run Code Online (Sandbox Code Playgroud) 好的,我有一个 axum 处理程序,看起来有点像这样:
#[debug_handler]
async fn handler(
State(server_state): State<Arc<Server>>,
Query(query_params): Query<Query>,
) -> impl IntoResponse {
match server_state.store.handle(query_params).await {
Ok(res) => (StatusCode::OK, Json(res)),
Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err))
}
}
Run Code Online (Sandbox Code Playgroud)
此操作失败并出现以下错误:
|
42 | / match server_state.store.handle(query_params).await {
43 | | Ok(res) => (StatusCode::OK, Json(res)),
| | -------------------------- this is found to be of type `(StatusCode, axum::Json<Vec<Data>>)`
44 | | Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, Json(err))
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Vec`, found enum `sqlx::Error`
45 | | }
| |_____- `match` arms …Run Code Online (Sandbox Code Playgroud) 我正在尝试向每个跟踪事件添加请求 ID。tower_http::trace我可以这样做:
#[derive(Clone)]
pub struct RequestSpan;
impl<B> tower_http::trace::MakeSpan<B> for RequestSpan {
fn make_span(&mut self, request: &http::Request<B>) -> tracing::Span {
tracing::error_span!(
"rq",
id = %ulid::Ulid::new().to_string(),
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
)
}
}
...
let middleware_stack = tower::ServiceBuilder::new()
.layer(TraceLayer::new_for_http().make_span_with(RequestSpan))
Run Code Online (Sandbox Code Playgroud)
它在服务器范围内工作,但我还需要将请求 ID 传递到外部任务队列中。有什么建议么?
我正在使用axum此代码来创建服务器,但出现错误:
use axum::{response::Html, routing::get, Router};
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}
#[tokio::main]
async fn main() {
let router = Router::new();
router.route("/", get(handler));
if true { // I need to check something here
router.route("/other", get(handler));
}
axum::Server::bind(&([127, 0, 0, 1], 3000).into())
.serve(router.into_make_service())
.await
.unwrap();
}
Run Code Online (Sandbox Code Playgroud)
error[E0382]: use of moved value: `router`
--> src\main.rs:18:16
|
9 | let router = Router::new();
| ------ move occurs because `router` has type `Router`, which does not implement the `Copy` …Run Code Online (Sandbox Code Playgroud) 我似乎找不到如何为响应设置标头。
我一直在寻找如何做到这一点,但还没有找到一个简单的方法来做到这一点。
特别强调标content-type头,如何从响应处理程序设置标准标头和自定义标头,记住我已经可以做到thing.into_response()。
我将从这个示例开始学习如何将 Axum 与 SQLx 结合使用。基本示例有效,但我在尝试继续前进时遇到问题。我正在使用一个简单的数据库表,如下所示:
todo | description
--------+--------------
todo_1 | doing todo 1
todo_2 | doing todo 2
todo_3 | doing todo 3
Run Code Online (Sandbox Code Playgroud)
我试图简单地返回“SELECT * FROM todos”,但出现错误。我认为我返回的类型是Result错误的,但我不知道下一步该怎么做。全文main.rs如下所示。
//! Example of application using <https://github.com/launchbadge/sqlx>
//!
//! Run with
//!
//! ```not_rust
//! cd examples && cargo run -p example-sqlx-postgres
//! ```
//!
//! Test with curl:
//!
//! ```not_rust
//! curl 127.0.0.1:3000
//! curl -X POST 127.0.0.1:3000
//! ```
use axum::{
async_trait,
extract::{Extension, FromRequest, …Run Code Online (Sandbox Code Playgroud) rust ×9
rust-axum ×9
rust-tower ×2
cors ×1
http-headers ×1
hyper ×1
rust-sqlx ×1
rust-tokio ×1