1 use h2::client;
2 use http::{Method, Request};
3 use tokio::net::TcpStream;
4 use tokio_rustls::TlsConnector;
5
6 use tokio_rustls::rustls::{OwnedTrustAnchor, RootCertStore, ServerName};
7
8 use std::error::Error;
9 use std::net::ToSocketAddrs;
10
11 const ALPN_H2: &str = "h2";
12
13 #[tokio::main]
main() -> Result<(), Box<dyn Error>>14 pub async fn main() -> Result<(), Box<dyn Error>> {
15 let _ = env_logger::try_init();
16
17 let tls_client_config = std::sync::Arc::new({
18 let mut root_store = RootCertStore::empty();
19 root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
20 OwnedTrustAnchor::from_subject_spki_name_constraints(
21 ta.subject,
22 ta.spki,
23 ta.name_constraints,
24 )
25 }));
26
27 let mut c = tokio_rustls::rustls::ClientConfig::builder()
28 .with_safe_defaults()
29 .with_root_certificates(root_store)
30 .with_no_client_auth();
31 c.alpn_protocols.push(ALPN_H2.as_bytes().to_owned());
32 c
33 });
34
35 // Sync DNS resolution.
36 let addr = "http2.akamai.com:443"
37 .to_socket_addrs()
38 .unwrap()
39 .next()
40 .unwrap();
41
42 println!("ADDR: {:?}", addr);
43
44 let tcp = TcpStream::connect(&addr).await?;
45 let dns_name = ServerName::try_from("http2.akamai.com").unwrap();
46 let connector = TlsConnector::from(tls_client_config);
47 let res = connector.connect(dns_name, tcp).await;
48 let tls = res.unwrap();
49 {
50 let (_, session) = tls.get_ref();
51 let negotiated_protocol = session.alpn_protocol();
52 assert_eq!(Some(ALPN_H2.as_bytes()), negotiated_protocol);
53 }
54
55 println!("Starting client handshake");
56 let (mut client, h2) = client::handshake(tls).await?;
57
58 println!("building request");
59 let request = Request::builder()
60 .method(Method::GET)
61 .uri("https://http2.akamai.com/")
62 .body(())
63 .unwrap();
64
65 println!("sending request");
66 let (response, other) = client.send_request(request, true).unwrap();
67
68 tokio::spawn(async move {
69 if let Err(e) = h2.await {
70 println!("GOT ERR={:?}", e);
71 }
72 });
73
74 println!("waiting on response : {:?}", other);
75 let (_, mut body) = response.await?.into_parts();
76 println!("processing body");
77 while let Some(chunk) = body.data().await {
78 println!("RX: {:?}", chunk?);
79 }
80 Ok(())
81 }
82