redirect/
redirect.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::str::FromStr;

use slinger::record::HTTPRecord;
use slinger::ClientBuilder;

fn main() -> Result<(), Box<dyn std::error::Error>> {
  customize().unwrap();
  limit(3).unwrap();
  only_same_host().unwrap();
  jump().unwrap();
  Ok(())
}
fn custom(attempt: slinger::redirect::Attempt) -> slinger::redirect::Action {
  let s = attempt
    .response()
    .body()
    .as_ref()
    .unwrap()
    .to_string()
    .trim()
    .to_string();
  if s == *"slinger" {
    let u = http::Uri::from_str(format!("http://httpbin.org/get?{}=awesome", &s).trim()).unwrap();
    slinger::redirect::Action::Follow(u)
  } else {
    slinger::redirect::Action::None
  }
}

fn customize() -> Result<(), Box<dyn std::error::Error>> {
  let redirect = slinger::redirect::Policy::Custom(custom);
  let client = ClientBuilder::new().redirect(redirect).build().unwrap();
  let resp = client
    .get("http://httpbin.org/base64/c2xpbmdlcgo%3D")
    .send()?;
  assert!(resp.text().unwrap_or_default().contains("slinger=awesome"));
  Ok(())
}
fn limit(max_redirect: usize) -> Result<(), Box<dyn std::error::Error>> {
  let redirect = slinger::redirect::Policy::Limit(max_redirect);
  let client = ClientBuilder::new().redirect(redirect).build().unwrap();
  let resp = client.get("http://httpbin.org/redirect/10").send()?;
  let record = resp.extensions().get::<Vec<HTTPRecord>>().unwrap();
  assert_eq!(record.len(), 3);
  Ok(())
}

fn jump() -> Result<(), Box<dyn std::error::Error>> {
  let client = ClientBuilder::new().build().unwrap();
  let resp = client
    .get("http://httpbin.org/redirect-to?url=http://www.example.com/")
    .send()?;
  let record = resp.extensions().get::<Vec<HTTPRecord>>().unwrap();
  println!("{:?}", record);
  assert_eq!(record.len(), 2);
  Ok(())
}

fn only_same_host() -> Result<(), Box<dyn std::error::Error>> {
  let redirect = slinger::redirect::Policy::Custom(slinger::redirect::only_same_host);
  let client = ClientBuilder::new().redirect(redirect).build().unwrap();
  let resp = client
    .get("http://httpbin.org/redirect-to?url=http://www.example.com/")
    .send()?;
  let record = resp.extensions().get::<Vec<HTTPRecord>>().unwrap();
  println!("{:?}", record);
  assert_eq!(record.len(), 1);
  let redirect_record = resp.redirect_record().unwrap();
  println!("{:?}", redirect_record);
  assert_eq!(
    redirect_record.next,
    Some(http::Uri::from_static("http://www.example.com/"))
  );
  Ok(())
}