Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Created February 27, 2026 01:05
Show Gist options
  • Select an option

  • Save masakielastic/6f310e7ef9e04124fc54c0013e74310b to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/6f310e7ef9e04124fc54c0013e74310b to your computer and use it in GitHub Desktop.
tiny_http で TLS

tiny_http で TLS

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/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment