1

I have create a server using rocket to access the peer information of an ipfs URL

The program as follows



#[macro_use] extern crate rocket;
use rocket::local::asynchronous::Client;

use rocket::http::hyper::{Request, Response};
use std::collections::HashMap;

use rocket::futures::TryFutureExt;
use std::fmt::Error;
use serde_json::Value;

#[get("/")]
async  fn index(){
    // https://github.com/rust-lang/rust/issues/63502

    let client  = reqwest::Client::new();

    let data = r#"
        {
            "name": "ELKA",
            "age": 43,
            "phones": [
                "+44 1234567",
                "+44 2345678"
            ]
        }"#;
    let doc: Value = serde_json::from_str(data).unwrap();
    let resp   = client.post("https://_IPFS_URL:5001/api/v0/swarm/peers").send().await.unwrap();
     
    // How to get the JSON response?
    
    if resp.status().is_success() {
        println!("success!");
        println!("RESP: {:?}", resp);
    } else if resp.status().is_server_error() {
        println!("server error!");
        println!("Something else happened. \n Resp {:?} \n Status: {:?}", resp, resp.status());
    } else {
        println!("Something else happened. \n Resp {:?} \n Status: {:?}", resp, resp.status());
    }


}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}


Response from curl -X POST https://_IPFS_URL:5001/api/v0/swarm/peers is

{
   "Peers":[
      {
         "Addr":"/ip4/172.31.20.195/tcp/4001",
         "Peer":"183293203CY",
         "Latency":"",
         "Muxer":"",
         "Direction":0,
         "Streams":null
      }
   ]
}

It's unclear to me how to read the response as a JSON using rust I am using the reqwest library Would be grateful if anyone can give guidance.

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
not 0x12
  • 19,360
  • 22
  • 67
  • 133
  • [`Response::json`](https://docs.rs/reqwest/0.11.4/reqwest/struct.Response.html#method.json)? – Jmb Sep 15 '21 at 07:06
  • @Jmb Can you add your answer so I can try it – not 0x12 Sep 15 '21 at 07:12
  • Notice that you don't need to construct `doc` by parsing the string representation; the `serde_json::json!`-macro can [construct the value directly](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=dea76ad76c1c2944ff85d5a432add6df). – user2722968 Sep 15 '21 at 08:16
  • The reqwest repository contains a number of examples, including [json_dynamic](https://github.com/seanmonstar/reqwest/blob/master/examples/json_dynamic.rs). Have you tried following that? Note that you will need to compile reqwest with the `json` [feature](https://doc.rust-lang.org/cargo/reference/features.html#dependency-features). – eggyal Sep 15 '21 at 09:43
  • @eggyal they have examples with Tokio but not with Rocket , examples are incompatible with rocket framework – not 0x12 Sep 15 '21 at 09:51

1 Answers1

0

I can't do the full test, but below is the idea

What is expected is

## https://docs.ipfs.io/reference/http/api/#getting-started

> curl -X POST http://127.0.0.1:5001/api/v0/swarm/peers
{
  "Strings": [
    "/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",
    "/ip4/104.236.151.122/tcp/4001/p2p/QmSoLju6m7xTh3DuokvT3886QRYqxAzb1kShaanJgW36yx",
    "/ip4/104.236.176.52/tcp/4001/p2p/QmSoLnSGccFuZQJzRadHn95W2CrSFmZuTdDWP8HXaHca9z",
  ]
}

From the documentation https://docs.rs/reqwest/0.11.4/reqwest/struct.Response.html

#[derive(Deserialize)]
struct Peers {
    Strings: Vec<String>,
}

let resp   = client.post("https://_IPFS_URL:5001/api/v0/swarm/peers")
    .send().
    await.
    json::<Peers>().
    //-------^--------- Deserialize the json in Peers format
    await.
    unwrap();
   
println!("{}", resp.Strings);
Zeppi
  • 1,175
  • 6
  • 11