小编kmd*_*eko的帖子

Actix 2.0中如何从Request中获取Cookie

我想从请求中获取cookie的值。我发现在 Actix 0.xx 中,cookie 的值可以通过调用获取

fn get_cookie(req: HttpRequest) {
    let cookie = req.cookie("name") <-- Here

    return HttpResponse::Ok()
        .body(
            format!("{}", cookie);
        )
}
Run Code Online (Sandbox Code Playgroud)

我对 Rust 和 Actix 还很陌生。目前我正在从声明的函数解析它,该函数获取HttpRequest.headers(). 我不确定是否有像 Actix 0.xx 中那样直接获取 cookie 的方法

pub fn get_cookie(req: HttpRequest, name: &str) -> String {
    let cookie: Vec<&str> = req
        .headers()
        .get("cookie")
        .unwrap()
        .to_str()
        .unwrap()
        .split("&")
        .collect();

    let auth_token: Vec<&str> = cookie
        .into_iter()
        .filter(|each| {
            let body: Vec<&str> = each.split("=").collect();

            body[0] == name
        })
        .collect();

    let cookie_part: Vec<&str> = auth_token[0].split("=").collect();

    cookie_part[1].to_owned() …
Run Code Online (Sandbox Code Playgroud)

rust actix-web

7
推荐指数
1
解决办法
4319
查看次数

如何将结构从 Actix 中间件传递到处理程序?

我正在尝试为我的 Actix 应用程序编写一个身份验证中间件。在中间件中验证请求时,我调用数据库来检索必要的用户数据以验证传入的请求。一旦请求获得授权,我希望能够将此用户数据传递给处理程序,因为这将使我避免两次查询相同的数据。

我无法找到解决方案。到目前为止我能找到的最好的建议是“设置请求扩展”。似乎没有任何这方面的示例,而且围绕此的文档也太少,无法弄清楚这里要做什么。

rust actix-web

7
推荐指数
1
解决办法
2793
查看次数

为什么我不能将 &amp;&amp;mut 转换为 &amp;&amp; ?

此代码在 C++ 中编译:

int x = 5;
int *const px = &x;
int *const *const ppx = &px;
int const *const *const cppx = ppx;
Run Code Online (Sandbox Code Playgroud)

所以我尝试在 Rust 中做同样的事情:

let mut x: i32 = 5;
let px: &mut i32 = &mut x;
let ppx: &&mut i32 = &px;
let cppx: &&i32 = ppx;
Run Code Online (Sandbox Code Playgroud)

但是,这无法编译:

error[E0308]: mismatched types
 --> src/main.rs:5:23
  |
5 |     let cppx: &&i32 = ppx;
  |               -----   ^^^ types differ in mutability
  |               |
  |               expected due to this …
Run Code Online (Sandbox Code Playgroud)

rust

7
推荐指数
1
解决办法
91
查看次数

Why does Stream provide convenience methods on an extension trait instead of the trait itself?

Consider the Iterator trait from the standard library:

pub trait Iterator {
    type Item;

    // required
    pub fn next(&mut self) -> Option<Self::Item>;

    // potentially advantageous to override
    pub fn size_hint(&self) -> (usize, Option<usize>) { ... }
    pub fn count(self) -> usize { ... }
    pub fn last(self) -> Option<Self::Item> { ... }
    pub fn advance_by(&mut self, n: usize) -> Result<(), usize> { ... }
    pub fn nth(&mut self, n: usize) -> Option<Self::Item> { ... }

    // convenience
    pub fn step_by(self, …
Run Code Online (Sandbox Code Playgroud)

traits rust

7
推荐指数
1
解决办法
77
查看次数

由于 *mut u8,异步块创建的 Future 不是 `Send`

我能够继续实现我的异步 udp 服务器。但是,此错误出现两次,因为我的变量数据的类型*mut u8不是Send

error: future cannot be sent between threads safely
 help: within `impl std::future::Future`, the trait `std::marker::Send` is not implemented for `*mut u8`
note: captured value is not `Send`
Run Code Online (Sandbox Code Playgroud)

和代码(MRE):

use std::error::Error;
use std::time::Duration;
use std::env;
use tokio::net::UdpSocket;
use tokio::{sync::mpsc, task, time}; // 1.4.0
use std::alloc::{alloc, Layout};
use std::mem;
use std::mem::MaybeUninit;
use std::net::SocketAddr;

const UDP_HEADER: usize = 8;
const IP_HEADER: usize = 20;
const AG_HEADER: usize = 4;
const MAX_DATA_LENGTH: usize = (64 …
Run Code Online (Sandbox Code Playgroud)

rust debouncing rust-tokio

7
推荐指数
1
解决办法
1万
查看次数

如何处理具有动态参数集的函数?

某些库(例如 Bevy 或 Actix Web)具有接受带有任意数量参数的用户定义函数的函数。

Actix 网站:

async fn fn1(path: web::Path<String>) -> impl Responder {
    // not important 
}

async fn fn2(_req: HttpRequest) -> impl Responder {
    // not important
}

let app = App::new()
    .route("/", web::get().to(fn2))
    .route("/{name}", web::get().to(fn1));
Run Code Online (Sandbox Code Playgroud)

贝维:

fn fn1(mut commands: Commands) {}
fn fn2(mut commands: Commands, time: Res<Time>) {}

App::new().add_system(fn1).add_system(fn2);
Run Code Online (Sandbox Code Playgroud)

正如您在这两种情况下所看到的,函数web::get().to(), add_system()接受具有动态数量和类型的参数的函数作为其参数。它们不是宏。我怎样才能实现这个目标?这个有名字吗?谢谢

rust

7
推荐指数
1
解决办法
1994
查看次数

如何拥有实现 2 个特征的 Boxes 向量?

在 Rust 中,我想要一个包含实现 2 个特征的项目的 vec。但是,当我尝试像这样实现它时,我收到错误only auto traits can be used as additional traits in a trait object

let mut v : Vec<Box<dyn MyTrait + std::fmt::Display>> = Vec::new();
Run Code Online (Sandbox Code Playgroud)

FairPlay,我完整阅读了错误消息并定义了一个结合了两者的 Trait:

pub trait FormattableDoer: std::fmt::Display + MyTrait{}
Run Code Online (Sandbox Code Playgroud)

它们有一个 Vec of Boxes:

let mut v: Vec<Box<dyn FormattableDoer>> = Vec::new();
Run Code Online (Sandbox Code Playgroud)

然而,编译器似乎无法检测到我的结构已经单独实现了这些东西,并且我收到了错误the trait bound MyStruct: FormattableDoer is not satisfied

我读到过有关使用特征别名的信息,但它不稳定,所以我宁愿不使用它。

这在生锈中可能吗?这似乎是一件很常见的事情,但我很惊讶答案并不简单(或者也许很简单,但我错过了!)。我也在想,也许我处理这个问题的方法完全错误,我正在尝试以“不生锈”的方式做一些事情。如果是这样的话,拥有可显示且具有其他特征的事物向量的首选方式是什么?

带有 MWE 和用例的Playground 。

vector traits rust

7
推荐指数
1
解决办法
1012
查看次数

如何从 axum 服务器路由调用结构方法?

我想实例化一个 struct 实例,然后在 api 路由中调用该实例的方法。这是我想要的示例,但它会导致错误:

use axum::{http::StatusCode, routing::get, Router, Server};

#[derive(Clone)]
struct Api {
    name: String
}

impl Api {
    async fn hello(&self) -> Result<String, StatusCode> {
        Ok(format!("Hello {}!", self.name))
    }
}

#[tokio::main]
async fn main() {
    let api = Api { name: "Alice".to_owned() };

    let app = Router::new()
        .route("/hello-user", get(api.hello));

    Server::bind(&([127, 0, 0, 1], 3000).into())
        .serve(app.into_make_service())
        .await
        .unwrap();
}
Run Code Online (Sandbox Code Playgroud)
use axum::{http::StatusCode, routing::get, Router, Server};

#[derive(Clone)]
struct Api {
    name: String
}

impl Api {
    async fn hello(&self) -> Result<String, …
Run Code Online (Sandbox Code Playgroud)

rust rust-axum

7
推荐指数
1
解决办法
1475
查看次数

我应该如何构建 Rust 项目来解决小的编码挑战?

我做欧拉项目问题(数学编码挑战)已经有一段时间了。

过去我一直用 Python 编写它们(在同一个项目中很容易有几十个脚本)。然而,我现在在学习 Rust 时正在重做一些挑战。我发现处理这些项目非常尴尬,因为我不能简单地在同一目录中编写一堆 Rust 程序,但为每个程序创建一个全新的 Rust 项目似乎也很过分。

谁能推荐一个好的中介吗?理想情况下,我正在寻找类似于前面提到的带有一堆单独脚本的 Python 项目的东西。

project-structure rust

7
推荐指数
1
解决办法
645
查看次数

为什么 println! 内联变量语法看起来不一致?

let a = [10, 20, 30, 40, 50];
let mut index_ = 0;
while index_ < 5 {
    println!("{}", a[index_]); // works
    println!("{a[index_]}");   // does not work
    println!("{index_}");      // works
    println!("{}", index_);    // works
    index_ = index_ + 1;
}
Run Code Online (Sandbox Code Playgroud)

为什么不起作用"{a[index_]}"?对我来说似乎应该如此。

syntax rust

7
推荐指数
1
解决办法
630
查看次数