Cargo.toml
[package]
name = "tiny-http-tls-example"
version = "0.1.0"
edition = "2021"
[dependencies]
tiny_http = { version = "0.12", features = ["ssl-rustls"] }
src/main.rs
use std::{fs, io, path::Path};
use tiny_http::{Response, Server, SslConfig};
fn read_all(path: impl AsRef<Path>) -> io::Result<Vec<u8>> {
fs::read(path)
}
fn main() -> io::Result<()> {
// PEM をそのまま読み込んで Vec<u8> として渡す(tiny_http の SslConfig はバイト列)
// certificate: サーバー証明書(必要ならチェーン込み)
// private_key: 秘密鍵(PEM)
let ssl = SslConfig {
certificate: read_all("cert.pem")?,
private_key: read_all("key.pem")?,
};
let server = Server::https("0.0.0.0:8443", ssl)
.expect("failed to start https server (check cert/key and feature flags)");
eprintln!("listening on https://127.0.0.1:8443");
for request in server.incoming_requests() {
// https で受けているか(tiny_http の ssl サーバー例でも secure() を確認している)
if !request.secure() {
eprintln!("WARNING: received non-secure request?");
}
eprintln!("{} {}", request.method(), request.url());
let body = format!("hello over TLS! path={}\n", request.url());
let response = Response::from_string(body);
let _ = request.respond(response);
}
Ok(())
}
cargo run
curl -v -k https://localhost:8443/