Module rama::dns::layer

source ·
Expand description

Layer to allow custom DNS Resolution within Rama.

§Example

use rama::dns::layer::{DnsLayer, DynamicDnsResolver};
use rama::http::service::web::{WebService, extract::{Host, Extension}};
use rama::http::{Body, Request, RequestContext, Version, StatusCode};
use rama::service::{Context, Service, Layer};
use rama::net::stream::ServerSocketAddr;
use rama::net::Protocol;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let dns_layer = DnsLayer::new()
        .dns_map_header("x-dns-map".parse().unwrap())
        .default_resolver();

    let service = dns_layer.layer(WebService::default()
        .get("/", |Host(host): Host, Extension(resolved): Extension<ServerSocketAddr>| async move {
            assert_eq!(host, "www.example.com");
            let expected_addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
            assert_eq!(resolved.addr(), &expected_addr);
            StatusCode::OK
        }),
    );

    let mut ctx = Context::default();
    ctx.insert(RequestContext{
        http_version: Version::HTTP_11,
        protocol: Protocol::Http,
        authority: Some("www.example.com:80".try_into().unwrap()),
    });

    let resp = service.serve(
        ctx,
        Request::builder()
            .uri("http://www.example.com")
            .header("x-dns-map", "www.example.com:80=127.0.0.1:8080")
            .body(Body::empty()).unwrap(),
    ).await.unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}

Structs§

Enums§

Traits§

  • An implementation of DynamicDnsResolver is used to resolve a hostname to a set of Socket addresses at runtime.