- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想实现一个阻塞函数,它发送一个带有 JSON 正文的 POST 请求并返回响应的 JSON 对象:
extern crate tokio_core;
extern crate rustc_serialize;
extern crate hyper;
extern crate futures;
use std::str;
use rustc_serialize::json;
use rustc_serialize::{Decoder, Decodable};
use hyper::{Method, Uri};
use hyper::client::{Client, Request};
use self::tokio_core::reactor::Core;
use self::futures::{Future, Stream};
#[derive(Debug, Clone)]
pub struct FooBar {
pub foo: String,
pub bar: String
}
impl Decodable for FooBar {
fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
d.read_struct("root", 0, |d| {
Ok(FooBar {
foo: try!(d.read_struct_field("foo", 0, |d| Decodable::decode(d))),
bar: try!(d.read_struct_field("bar", 1, |d| Decodable::decode(d)))
})
})
}
}
fn send_request(url: Uri, obj: json::Object) -> Option<FooBar> {
let mut core = Core::new().unwrap();
let client = Client::new(&core.handle());
let msg = json::encode(&obj).unwrap();
let mut request = Request::new(Method::Post, url);
request.set_body(msg.as_bytes());
let mut response = client.request(request).wait().unwrap();
assert_eq!(response.status(), hyper::Ok);
let res_vec = response.body().concat2().wait().unwrap().to_vec();
let res_str = str::from_utf8(&res_vec).unwrap();
return match json::decode(&res_str) {
Ok(res_obj) => Some(res_obj),
Err(err) => {
println!("{}", err);
None
}
}
}
我得到的错误是 msg
的生命周期不够长:
error[E0597]: `msg` does not live long enough
--> src/test.rs:37:22
|
37 | request.set_body(msg.as_bytes());
| ^^^ does not live long enough
...
51 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...
此时我有两个问题:
msg
在静态生命周期内有效?从消息中我不清楚。msg
在静态生命周期内有效的情况下实现这样的功能?就我而言,这不是一个可行的解决方案。依赖关系:
rustc-serialize = "0.3"
futures = "0.1"
hyper = "0.11"
tokio-core = "0.1"
最佳答案
request.set_body()
采用需要转换为 hyper::Body
的参数(B
中 hyper::client::Request<B>
的默认值)。
如果您查看 From
的列表( Into
的“双重”特性) hyper::Body
的实现你会看到impl From<&'static [u8]> for Body
- 这是您静态生命周期要求的来源(没有 impl<'a> From<&'a [u8]> for Body
会采用任何其他对“字节”的引用)。
但您还会看到 impl From<String> for Body
- 所以只通过 msg
应该没问题(据我所知应该是 String
)而不是 msg.as_bytes()
至 request.set_body()
.它将取得字符串 msg
的所有权, 所以你以后不能再自己使用它了。
关于rust - 请求消息值必须在静态生命周期内有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970966/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!