我希望我的 Rocket API 有这样的路线:
#[post("create/thing", format = "application/json", data="<thing>")]
Run Code Online (Sandbox Code Playgroud)
当客户端发送时{ "name": "mything" }
,一切都应该没问题,我知道该怎么做,但是当它发送时,{ "name": "foo" }
它应该响应如下:
#[post("create/thing", format = "application/json", data="<thing>")]
Run Code Online (Sandbox Code Playgroud)
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Run Code Online (Sandbox Code Playgroud)
我如何以 JSON 对象和与 Rocket 中的 200 不同的 HTTP 状态代码之类的结果进行响应?
这是我到目前为止尝试过的:
impl
FromRequest
对于我的Thing
类型。这让我可以选择一个状态代码,因为我可以编写自己的from_request
函数,但我不能返回任何其他内容。我有一个在main
(第 9 行)中初始化的变量,我想在我的一个路由处理程序中访问对这个变量的引用。
#[get("/")]
fn index() -> String {
return fetch_data::fetch(format!("posts"), &redis_conn).unwrap(); // How can I get redis_conn?
}
fn main() {
let redis_conn = fetch_data::get_redis_connection(); // initialized here
rocket::ignite().mount("/", routes![index]).launch();
}
Run Code Online (Sandbox Code Playgroud)
在其他语言中,这个问题可以通过使用全局变量来解决。
我创建了一个存储库,其中包含基于 Node.js和基于Rocket.rs 的Web 服务器。
考虑以下步骤:
cargo run --release
node server.js
我也用 actix-web 观察到类似的事情,但程度较小:在这种情况下,如果我没有刷新选项卡大约 5 秒,我只会得到大约 300 毫秒的延迟。如果我不断刷新它,那么请求会在 5 毫秒内完成。
有趣的是,延迟似乎如果我通过像袅袅衡量不会出现这种与此。我的两台服务器都有大约 4 毫秒的延迟。
我注意到 Rocket 和 actix-web 不会在他们的响应中发送 Keep-Alive 标头。如果我理解正确,这对于 HTTP 1.1 请求应该无关紧要。
我正在使用安装了 Ubuntu 的 WSL 2。Chrome 在主机 Windows 中运行。
有人可以解释一下这里发生了什么吗?
更新:忘了说我是使用夜间编译器来构建火箭服务器的(Rocket v0.4.6 似乎需要它)。直接从主分支更改为稳定和构建摆脱了延迟。尽管如此,actix-web 延迟仍然有点令人担忧,因为我使用了稳定的编译器。
尝试编译:https://github.com/SergioBenitez/Rocket/tree/master/examples/hello
Cargo.toml
[dependencies]
rocket = "0.4.10"
Run Code Online (Sandbox Code Playgroud)
抱怨我每晚都需要 Rust
$ cargo build
...
Error: Rocket (core) requires a more recent version of rustc.
Installed version: 1.54.0 (2021-05-17)
Minimum required: 1.54.0-nightly (2021-05-18)
Run Code Online (Sandbox Code Playgroud)
我已经完成了本地目录覆盖
$ rustup override set nightly
Run Code Online (Sandbox Code Playgroud)
我每晚运行 2021-05-17 但我需要 2021-05-18
$ rustup show
...
active toolchain
----------------
nightly-x86_64-unknown-linux-gnu (directory override for '/<redacted>')
rustc 1.54.0-nightly (3e99439f4 2021-05-17)
Run Code Online (Sandbox Code Playgroud)
我尝试了各种命令来获取更新的每晚
$ rustup update
$ rustup update nightly
$ rustup toolchain install nightly-2021-05-18
Run Code Online (Sandbox Code Playgroud)
当我这样做的时候,会发生一些奇怪的事情rustup update nightly
$ rustup update nightly
info: syncing …
Run Code Online (Sandbox Code Playgroud) 在 Rust 中通过 Rocket 返回 Json 最简单的方法是什么?
#[post("/route", data = "<data>")]
fn route(someVariable: String) -> String {
// How can I return a json response here? {"a": "{someVariable}")
}
Run Code Online (Sandbox Code Playgroud)
我尝试过:content::Json()
但对我来说似乎太静态了。
我正在使用 Rocket 框架,我想在我的处理程序中发出一个异步 HTTP 请求,就像这样
#[get("/")]
async fn handler() -> String {
some_func().await;
"OK".into()
}
Run Code Online (Sandbox Code Playgroud)
结果,我得到了下一个错误
#[get("/")]
async fn handler() -> String {
some_func().await;
"OK".into()
}
Run Code Online (Sandbox Code Playgroud)
我试图编写实现但失败了。有没有办法为 impl Trait 实现 trait?
或者可以指定 async fn 的返回类型,以便我可以返回实现了必要特征的自定义类型?
我按照快速入门指南进行操作。现在我试图返回一些超级简单的 JSON,但文档是错误的,并且无法在不进入 IRC 的情况下提交票证。
error[E0432]: unresolved import `rocket::serde::json`
--> src/main.rs:2:20
|
2 | use rocket::serde::json::Json;
| ^^^^ could not find `json` in `serde`
For more information about this error, try `rustc --explain E0432`.
error: could not compile `my-api` due to previous error
Run Code Online (Sandbox Code Playgroud)
Cargo.toml
[package]
name = "my-api"
version = "0.1.0"
edition = "2021"
publish = false
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rocket = "0.5.0-rc.1"
serde = "1.0.130"
Run Code Online (Sandbox Code Playgroud)
main.rs
[package]
name = …
Run Code Online (Sandbox Code Playgroud) 我正在使用 reqwest 查询 Google API:
let request_url = format!(
"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=*\
&inputtype=textquery\
&fields=formatted_address,name,place_id,types\
&locationbias=circle:50@{},{}\
&key=my-secret-key",
lat, lng
);
let mut response = reqwest::get(&request_url).expect("pffff");
let gr: GoogleResponse = response.json::<GoogleResponse>().expect("geeez");
Run Code Online (Sandbox Code Playgroud)
该GoogleResponse
结构体定义为
#[derive(Debug, Serialize, Deserialize)]
pub struct DebugLog {
pub line: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Candidate {
pub formatted_address: String,
pub name: String,
pub place_id: String,
pub types: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GoogleResponse {
pub candidates: Vec<Candidate>,
pub debug_log: DebugLog,
pub status: String,
}
Run Code Online (Sandbox Code Playgroud)
这一切都会编译,我可以发出请求,但是我在字段中得到的结果String …
我创建了一个 docker 镜像,其中包含一个 rust 应用程序,该应用程序响应端口 8000 上的获取请求。应用程序本身是一个使用火箭库 ( https://rocket.rs/ )的基本示例,它看起来像这样
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
fn main() {
rocket::ignite().mount("/", routes![index]).launch();
}
Run Code Online (Sandbox Code Playgroud)
我已经编译了这个并称之为 server
然后我创建了一个 Docker 文件来托管它
FROM ubuntu:16.04
RUN apt-get update; apt-get install -y curl
COPY server /root/
EXPOSE 8000
CMD ["/root/server"]
Run Code Online (Sandbox Code Playgroud)
我构建 docker 镜像
$ docker build -t port_test
并运行它$ docker run -p 8000:8000 port_test
在这一点上,一切看起来都不错
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES …
Run Code Online (Sandbox Code Playgroud) 我会在Python中使用flask做这样的事情:
@app.route('/login/', methods=['POST'])
def login():
token = request.headers["token"]
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何访问token
标头并将其存储为String
变量。
#![feature(proc_macro_hygiene, decl_macro)]
use rocket::{
config::{Config, Environment},
*,
};
fn main() {
let config = Config::build(Environment::Production)
.address("0.0.0.0")
.port(PORT)
.finalize()
.unwrap();
rocket::ignite().mount("/", routes![login]).launch();
}
#[post("/login")]
fn login() {
// Retrieve headers from request.
}
Run Code Online (Sandbox Code Playgroud) rust ×10
rust-rocket ×10
async-await ×1
curl ×1
docker ×1
http-headers ×1
json ×1
latency ×1
networking ×1
node.js ×1
performance ×1
rest ×1
serde ×1
traits ×1