The example for dynamic json with reqwest
extern crate reqwest;
extern crate tokio;
extern crate serde_json; // added to after upgrade to 1.39.0
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
let echo_json: serde_json::Value = reqwest::Client::new()
.post("https://jsonplaceholder.typicode.com/posts")
.json(&serde_json::json!({
"title": "Reqwest.rs",
"body": "https://docs.rs/reqwest",
"userId": 1
}))
.send()
.await?
.json()
.await?;
println!("{:#?}", echo_json);
// Object(
// {
// "body": String(
// "https://docs.rs/reqwest"
// ),
// "id": Number(
// 101
// ),
// "title": String(
// "Reqwest.rs"
// ),
// "userId": Number(
// 1
// )
// }
// )
Ok(())
}
failed to compile for rustc 1.38.0 with reqwest = "0.9.22" and tokio = "0.2.2":
Compiling pin-project-lite v0.1.1
error: `core::slice::<impl [T]>::len` is not yet stable as a const fn
--> /Users/mick/.cargo/registry/src/github.com-1ecc6299db9ec823/bytes-0.5.2/src/bytes.rs:121:18
|
121 | len: bytes.len(),
| ^^^^^^^^^^^
error: aborting due to previous error
error: Could not compile `bytes`.
This was fixed by upgrading as of the comment by Ömer below, but now the next problems are
error[E0433]: failed to resolve: could not find `main` in `tokio`
--> main.rs:5:10
|
5 | #[tokio::main]
| ^^^^ could not find `main` in `tokio`
error[E0277]: the trait bound `std::result::Result<reqwest::Response, reqwest::Error>: std::future::Future` is not satisfied
--> main.rs:7:40
|
7 | let echo_json: serde_json::Value = reqwest::Client::new()
| ________________________________________^
8 | | .post("https://jsonplaceholder.typicode.com/posts")
9 | | .json(&serde_json::json!({
10 | | "title": "Reqwest.rs",
... |
14 | | .send()
15 | | .await?
| |______________^ the trait `std::future::Future` is not implemented for `std::result::Result<reqwest::Response, reqwest::Error>`
error[E0277]: `main` has invalid return type `impl std::future::Future`
--> main.rs:6:20
|
6 | async fn main() -> Result<(), reqwest::Error> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` can only return types that implement `std::process::Termination`
|
= help: consider using `()`, or a `Result`
error: aborting due to 3 previous errors
Some errors have detailed explanations: E0277, E0433.
For more information about an error, try `rustc --explain E0277`.
error: could not compile `webtrekk`.
To learn more, run the command again with --verbose.
and the next reqwest = "0.10.0-alpha.2" tokio = { version = "0.2.2", features = ["macros"] } serde_json = "1.0.44"
➜ rust git:(master) ✗ cargo run
Updating crates.io index
error: failed to select a version for `tokio`.
... required by package `reqwest v0.10.0-alpha.2`
... which is depended on by `webtrekk v0.1.0 (/Users/mick/repo/webtrekk-client/rust)`
versions that meet the requirements `= 0.2.0-alpha.6` are: 0.2.0-alpha.6
all possible versions conflict with previously selected packages.
previously selected package `tokio v0.2.2`
... which is depended on by `webtrekk v0.1.0 (/Users/mick/repo/webtrekk-client/rust)`
failed to select a version for `tokio` which could resolve this conflict
How can these be fixed?
Your example comes from https://github.com/seanmonstar/reqwest/blob/master/examples/json_dynamic.rs and works with the following Cargo.toml, using Rust 1.39:
[package]
name = "reqwest-json_dynamic-example"
version = "0.1.0"
authors = ["fyaa"]
edition = "2018"
[dependencies]
tokio = { version = "=0.2.0-alpha.6", features = ["io", "tcp", "timer"] }
reqwest = { version = "0.10.0-alpha.2", features = ["json"] }
serde_json = "1.0.44"
Related
In the tokio tests I see they use oneshot::channel together with serve_with_shutdown but the the compiler tells me to add use futures_util::future::future::FutureExt but as you can see in the example below I already added that trait to the scope.
What am I missing?
Here a reprex
run cargo new tokio-test
Cargo.toml
[package]
name = "tokio-test"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tonic = "0.7"
prost = "0.10.1"
tokio = { version = "1.18", features = ["macros", "rt-multi-thread"] }
[build-dependencies]
tonic-build = "0.7.2"
src/main.rs
pub mod console {
tonic::include_proto!("console");
}
use console::console_server::{Console, ConsoleServer};
use console::{ConsoleResponse, InfoRequest};
use tokio::runtime::Runtime;
use tokio::sync::oneshot;
use tonic::{transport::Server, Request, Response};
use futures_util::FutureExt;
#[derive(Default)]
pub struct ConsoleImpl {}
#[tonic::async_trait]
impl Console for ConsoleImpl {
async fn info(
&self,
request: Request<InfoRequest>,
) -> Result<Response<ConsoleResponse>, tonic::Status> {
println!("{}", request.get_ref().text);
Ok(Response::new(ConsoleResponse {}))
}
}
fn main() {
let addr = "[::1]:50051".parse().unwrap();
let maxconsole = ConsoleImpl::default();
println!("Console server listening on {}", addr);
let mut rt = Runtime::new().expect("failed to obtain a new RunTime object");
let (shutdown_send, shutdown_recv) = oneshot::channel::<()>();
let server_future = Server::builder()
.add_service(ConsoleServer::new(maxconsole))
// .serve(addr)
.serve_with_incoming_shutdown(
addr,
shutdown_recv.map(drop),
);
rt.block_on(server_future).expect("failed to successfully run the future on RunTime");
}
src/console.proto
syntax = "proto3";
package console;
service Console {
rpc info (InfoRequest) returns (ConsoleResponse) {}
}
message InfoRequest {
string text = 1;
}
message ConsoleResponse {
}
If you build the project it will complain
❯ cargo build
Updating crates.io index
Compiling tokio-test v0.1.0 (C:\s\tokio-test)
error[E0432]: unresolved import `futures_util`
--> src\main.rs:10:5
|
10 | use futures_util::FutureExt;
| ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`
error[E0599]: `tokio::sync::oneshot::Receiver<()>` is not an iterator
--> src\main.rs:40:27
|
40 | shutdown_recv.map(drop),
| ^^^ `tokio::sync::oneshot::Receiver<()>` is not an iterator
|
::: C:\Users\FrancescElies\.cargo\registry\src\github.com-1ecc6299db9ec823\tokio-1.20.1\src\sync\oneshot.rs:318:1
|
318 | pub struct Receiver<T> {
| ---------------------- doesn't satisfy `tokio::sync::oneshot::Receiver<()>: Iterator`
|
= note: the following trait bounds were not satisfied:
`tokio::sync::oneshot::Receiver<()>: Iterator`
which is required by `&mut tokio::sync::oneshot::Receiver<()>: Iterator`
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
1 | use futures_util::future::future::FutureExt;
|
Some errors have detailed explanations: E0432, E0599.
For more information about an error, try `rustc --explain E0432`.
error: could not compile `tokio-test` due to 2 previous errors
Yes, you added the FutureExt import, but did not tell Rust where to find that crate. The critical part of the error message is:
error[E0432]: unresolved import `futures_util`
--> src\main.rs:10:5
|
10 | use futures_util::FutureExt;
| ^^^^^^^^^^^^ use of undeclared crate or module `futures_util`
This can be fixed by adding the futures_util crate to your Cargo.toml dependency section.
I'm a rust newbie and I'm having a lot of trouble getting some simple ws examples to run.
I have a new project with this in the Cargo.toml file:
[package]
name = "ouranos4"
version = "0.1.0"
authors = ["jasongoodwin <jay.michael.goodwin#gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tokio = { version = "1", features = ["full"] }
warp = "0.3"
And then I have the warp ws example found here: https://github.com/seanmonstar/warp/blob/master/examples/websockets.rs
// use futures::{FutureExt, StreamExt};
use warp::Filter;
#[tokio::main]
async fn main() {
let routes = warp::path("echo")
// The `ws()` filter will prepare the Websocket handshake.
.and(warp::ws())
.map(|ws: warp::ws::Ws| {
// And then our closure will be called when it completes...
ws.on_upgrade(|websocket| {
// Just echo all messages back...
let (tx, rx) = websocket.split();
rx.forward(tx).map(|result| {
if let Err(e) = result {
eprintln!("websocket error: {:?}", e);
}
})
})
});
warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
And I swear this was compiling but out of the blue I'm getting these errors:
Compiling ouranos4 v0.1.0 (/Users/jasongoodwin/Development/src/ouranos4)
error[E0599]: no method named `split` found for struct `WebSocket` in the current scope
--> src/main.rs:13:42
|
13 | let (tx, rx) = websocket.split();
| ^^^^^ method not found in `WebSocket`
|
::: /Users/jasongoodwin/.cargo/registry/src/github.com-1ecc6299db9ec823/futures-util-0.3.14/src/stream/stream/mod.rs:1359:8
|
1359 | fn split<Item>(self) -> (SplitSink<Self, Item>, SplitStream<Self>)
| ----- the method is available for `Box<WebSocket>` here
|
= help: items from traits can only be used if the trait is in scope
help: the following trait is implemented but not in scope; perhaps add a `use` for it:
|
2 | use futures_util::stream::stream::StreamExt;
|
error: aborting due to previous error
For more information about this error, try `rustc --explain E0599`.
error: could not compile `ouranos4`
I've recreated the project, cleaned the project, done everything imaginable. Switched the rust compiler version to nightly and back.
I'm really confused as to why I can't split this now. I've tried different examples, different crates, and I keep seeing this error.
I'm tempted to throw my laptop away and try on a different computer :P
I needed to add some more imports!
Thanks to kmdreko.
use futures::StreamExt;
use futures::FutureExt;
For some reason it is telling me that it is undeclared when i am trying to follow an example for an IRC in rust and it makes no sense that it is not working cause i have used libraries like this before and it worked before so idk what is happening \
code:
use futures::prelude::*;
use irc::client::prelude::*;
#[tokio::main]
async fn main() -> irc::error::Result<()> {
let config = Config {
nickname: Some("pickles".to_owned()),
server: Some("chat.freenode.net".to_owned()),
channels: vec!["#rust-spam".to_owned()],
..Default::default()
};
let mut client = Client::from_config(config).await?;
client.identify()?;
let mut stream = client.stream()?;
let sender = client.sender();
while let Some(message) = stream.next().await.transpose()? {
print!("{}", message);
match message.command {
Command::PRIVMSG(ref target, ref msg) => {
if msg.contains(client.current_nickname()) {
sender.send_privmsg(target, "Hi!")?;
}
}
_ => (),
}
}
Ok(())
}
Errors
--> src\main.rs:1:5
|
1 | use futures::prelude::*;
| ^^^^^^^ use of undeclared type or module `futures`
error[E0308]: mismatched types
--> src\main.rs:9:19
|
9 | channels: vec!["#rust-spam".to_owned()],
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| expected enum `std::option::Option`, found struct `std::vec::Vec`
| help: try using a variant of the expected enum: `Some(<[_]>::into_vec(box [$($x),+]))`
|
= note: expected enum `std::option::Option<std::vec::Vec<_>>`
found struct `std::vec::Vec<_>`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0599]: no function or associated item named `from_config` found for trait object `dyn irc::client::Client` in the current scope
--> src\main.rs:13:30
|
13 | let mut client = Client::from_config(config).await?;
| ^^^^^^^^^^^ function or associated item not found in `dyn irc::client::Client`
Cargo.toml
[package]
name = "irc"
version = "0.1.0"
authors = ["sudo"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
irc = "0.13"
tokio = { version = "0.2.22", features = ["full"] }
Edit: Added Cargo.toml
You will need to add the futures crate to your cargo file. E.g. from the docs
[dependencies]
futures = "0.3"
You need to add futures to your Cargo.toml, even though a dependency already depends on it.
This question already has answers here:
How do I fix "cannot find derive macro in this scope"?
(1 answer)
Why is a trait not implemented for a type that clearly has it implemented?
(1 answer)
Closed 2 years ago.
I'm trying to make a simple endpoint using Rocket. My Cargo.toml has these dependencies:
[dependencies]
rocket = "0.4.2"
rocket_codegen = "0.4.2"
rocket_contrib = "0.4.2"
main.rs looks like:
#[macro_use]
extern crate rocket;
use rocket_contrib::json::Json;
use serde::Serialize;
#[get("/org")]
fn getorg() -> Json<Org> {
Json(Org {
id: Option::from(25),
name: "Incredible-Customer".to_string(),
})
}
#[derive(Serialize)]
pub struct Org {
pub id: Option<i32>,
pub name: String,
}
fn main() {
rocket::ignite().mount("/", routes![getorg]).launch();
}
Compiling results in the errors:
error[E0432]: unresolved import `serde`
--> src/main.rs:3:5
|
3 | use serde::Serialize;
| ^^^^^ use of undeclared crate or module `serde`
error: cannot determine resolution for the derive macro `Serialize`
--> src/main.rs:14:10
|
14 | #[derive(Serialize)]
| ^^^^^^^^^
|
= note: import resolution is stuck, try simplifying macro imports
error[E0658]: `macro` is experimental
--> src/main.rs:7:1
|
7 | #[get("/org")]
| ^^^^^^^^^^^^^^
|
= note: see issue #39412 <https://github.com/rust-lang/rust/issues/39412> for more information
= help: add `#![feature(decl_macro)]` to the crate attributes to enable
= note: this error originates in an attribute macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0277]: the trait bound `Org: serde::ser::Serialize` is not satisfied
--> src/main.rs:8:16
|
8 | fn getorg() -> Json<Org> {
| ^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `Org`
|
::: /Users/shep/.cargo/registry/src/github.com-1ecc6299db9ec823/rocket-0.4.5/src/handler.rs:202:20
|
202 | pub fn from<T: Responder<'r>>(req: &Request, responder: T) -> Outcome<'r> {
| ------------- required by this bound in `handler::<impl rocket::Outcome<rocket::Response<'r>, rocket::http::Status, rocket::Data>>::from`
|
= note: required because of the requirements on the impl of `Responder<'_>` for `rocket_contrib::json::Json<Org>
I'm very confused as to how to look into this error. Is it a dependency issue? Why? I have versioned the rocket dependencies to the same one, but apparently this serde dependency is unhappy. Googling around claims it's a version mismatch inside one of my dependencies - but how do I go about solving that myself?
Add serde = {version = "1.0", features = ["derive"]} and serde_json = {version = "1.0"} to your cargo.toml to be able to derive from Serialize and Deserialize
This question already has an answer here:
How do I fix "cannot find derive macro in this scope"?
(1 answer)
Closed 2 years ago.
I am trying to Deserialize a string to a struct in rust. The below code is from json_serde documentation only.
use serde::{Deserialize, Serialize};
use serde_json::Result;
#[derive(Serialize, Deserialize)]
struct Person {
name: String,
age: u8,
phones: Vec<String>,
}
fn main() {
let data = r#"
{
"name": "John Doe",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
// Parse the string of data into a Person object. This is exactly the
// same function as the one that produced serde_json::Value above, but
// now we are asking it for a Person as output.
let p: Person = serde_json::from_str(data).expect("bal");
// Do things just like with any other Rust data structure.
println!("Please call {} at the number {}", p.name, p.phones[0]);
}
The above code snippet gives me an error:
Compiling test-json-rs v0.1.0 (/Users/asnimpansari/Desktop/Personal/test-json-rs)
error: cannot find derive macro `Serialize` in this scope
--> src/main.rs:4:10
|
4 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^
error: cannot find derive macro `Deserialize` in this scope
--> src/main.rs:4:21
|
4 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
warning: unused imports: `Deserialize`, `Serialize`
--> src/main.rs:1:13
|
1 | use serde::{Deserialize, Serialize};
| ^^^^^^^^^^^ ^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: unused import: `serde_json::Result`
--> src/main.rs:2:5
|
2 | use serde_json::Result;
| ^^^^^^^^^^^^^^^^^^
error[E0277]: the trait bound `Person: serde::de::Deserialize<'_>` is not satisfied
--> src/main.rs:25:21
|
25 | let p: Person = serde_json::from_str(data).expect("bal");
| ^^^^^^^^^^^^^^^^^^^^ the trait `serde::de::Deserialize<'_>` is not implemented for `Person`
|
::: /Users/asnimpansari/.cargo/registry/src/github.com-1ecc6299db9ec823/serde_json-1.0.55/src/de.rs:2584:8
|
2584 | T: de::Deserialize<'a>,
| ------------------- required by this bound in `serde_json::de::from_str`
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0277`.
error: could not compile `test-json-rs`.
To learn more, run the command again with --verbose.
My Cargo.toml file has below dependencies
[dependencies]
serde_json = "1.0.55"
serde = "1.0.100"
Despite importing Serialize and Deserialize from the serde and adding to struct. It gives me an error.
What part am I doing wrong here?
You need to activate the derive macros feature in your Cargo.toml:
serde = { version = "1.0", features = ["derive"] }