File: server_client.rs

package info (click to toggle)
rust-hyperlocal 0.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 164 kB
  • sloc: makefile: 2
file content (54 lines) | stat: -rw-r--r-- 1,414 bytes parent folder | download
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
#![allow(unused_imports)]
use std::{error::Error, fs, path::Path};

use hyper::{
    body::HttpBody,
    service::{make_service_fn, service_fn},
    Body, Client, Response, Server,
};
#[cfg(all(feature = "client", feature = "server"))]
use hyperlocal::{UnixClientExt, UnixServerExt, Uri};

#[tokio::test]
#[cfg(all(feature = "client", feature = "server"))]
async fn test_server_client() -> Result<(), Box<dyn Error + Send + Sync>> {
    let path = Path::new("/tmp/hyperlocal.sock");

    if path.exists() {
        fs::remove_file(path)?;
    }

    let make_service = make_service_fn(|_| async {
        Ok::<_, hyper::Error>(service_fn(|_req| async {
            Ok::<_, hyper::Error>(Response::new(Body::from("It works!")))
        }))
    });

    let (tx, rx) = tokio::sync::oneshot::channel::<()>();

    let server = Server::bind_unix("/tmp/hyperlocal.sock")?
        .serve(make_service)
        .with_graceful_shutdown(async { rx.await.unwrap() });

    tokio::spawn(async move { server.await.unwrap() });

    let client = Client::unix();

    let url = Uri::new(path, "/").into();

    let mut response = client.get(url).await?;
    let mut bytes = Vec::default();

    while let Some(next) = response.data().await {
        let chunk = next?;
        bytes.extend(chunk);
    }

    let string = String::from_utf8(bytes)?;

    tx.send(()).unwrap();

    assert_eq!(string, "It works!");

    Ok(())
}