Crates.io | test-helper |
lib.rs | test-helper |
version | 0.1.0 |
source | src |
created_at | 2021-03-19 04:15:18.865286 |
updated_at | 2021-03-19 04:15:18.865286 |
description | Helper functions for testing. |
homepage | https://github.com/tyrchen/test-helper |
repository | https://github.com/tyrchen/test-helper |
max_upload_size | |
id | 370867 |
size | 17,176 |
This code is modified and derived from tonic. It reduces the complexity of using TLS for your tokio TCP applications.
Usage:
Server:
// you could also build your config with cert and identity separately. See tests.
let config: ServerTlsConfig = toml::from_str(config_file).unwrap();
let acceptor = config.tls_acceptor().unwrap();
let listener = TcpListener::bind(addr).await.unwrap();
tokio::spawn(async move {
loop {
let (stream, peer_addr) = listener.accept().await.unwrap();
let stream = acceptor.accept(stream).await.unwrap();
info!("server: Accepted client conn with TLS");
let fut = async move {
let (mut reader, mut writer) = split(stream);
let n = copy(&mut reader, &mut writer).await?;
writer.flush().await?;
debug!("Echo: {} - {}", peer_addr, n);
}
tokio::spawn(async move {
if let Err(err) = fut.await {
error!("{:?}", err);
}
});
}
});
Client:
let msg = b"Hello world\n";
let mut buf = [0; 12];
// you could also build your config with cert and identity separately. See tests.
let config: ClientTlsConfig = toml::from_str(config_file).unwrap();
let connector = config.tls_connector(Uri::from_static("localhost")).unwrap();
let stream = TcpStream::connect(addr).await.unwrap();
let mut stream = connector.connect(stream).await.unwrap();
info!("client: TLS conn established");
stream.write_all(msg).await.unwrap();
info!("client: send data");
let (mut reader, _writer) = split(stream);
reader.read_exact(buf).await.unwrap();
info!("client: read echoed data");
Note TLS is one of many choices to secure your TCP connections, you may also consider snow which implemented Noise protocol.
tokio-tls-helper
is distributed under the terms of MIT.
See LICENSE for details.
Copyright 2021 Tyr Chen