add support to JSON's requests

master
kirbylife 2021-02-03 15:26:12 -06:00
parent c27ee1640b
commit c68ea948a6
4 changed files with 26 additions and 4 deletions

View File

@ -12,3 +12,5 @@ tokio = { version = "0.2", features = ["full"] }
url = "2.1"
http = "0.2"
nipper = "0.1.8"
serde_json = "1.0"
serde = "1.0"

View File

@ -1,7 +1,8 @@
use crate::response;
use http::status::StatusCode;
use url::{ParseError, Url};
use crate::response;
pub trait RequestBase {
fn new(url: &'static str) -> Result<Self, ParseError>
where

View File

@ -1,7 +1,9 @@
use crate::selector::SelectorBase;
use http::StatusCode;
use serde_json::{Result, Value};
use url::Url;
use crate::selector::SelectorBase;
#[derive(Debug)]
pub struct Response {
pub text: String,
@ -15,6 +17,14 @@ impl SelectorBase for Response {
}
fn html(&self) -> String {
format!("{}", self.text)
self.text.clone()
}
}
impl Response {
pub fn to_json(&self) -> Result<Value> {
let plain_text: &[u8] = self.text.as_ref();
let json = serde_json::from_slice(plain_text)?;
Ok(json)
}
}

View File

@ -75,4 +75,13 @@ fn complex_selectors() {
assert_eq!(node.content(), "link");
}
}
assert!(sel.css_once::<Selector>("h1").is_none());
}
#[test]
fn simple_json_test() {
let req: Request = RequestBase::new("https://httpbin.org/json").unwrap();
let resp = req.launch().to_json().expect("cannot parse json");
assert_eq!(resp["slideshow"]["title"], "Sample Slide Show");
}