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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
//! Gotham – A flexible web framework that promotes stability, safety, security and speed.
//!
//! You can find out more about Gotham, including where to get help, at <https://gotham.rs>.
//!
//! We look forward to welcoming you into the Gotham community!
#![doc(html_root_url = "https://docs.rs/gotham/0.7.2")] // Update when changed in Cargo.toml
#![warn(deprecated, missing_docs, unreachable_pub)]
// Stricter requirements once we get to pull request stage, all warnings must be resolved.
#![cfg_attr(feature = "ci", deny(warnings))]
#![cfg_attr(
    feature = "cargo-clippy",
    allow(
        clippy::needless_lifetimes,
        clippy::should_implement_trait,
        clippy::unit_arg,
        clippy::match_wild_err_arm,
        clippy::new_without_default,
        clippy::wrong_self_convention,
        clippy::mutex_atomic,
        clippy::borrowed_box,
        clippy::get_unwrap,
    )
)]
#![doc(test(no_crate_inject, attr(deny(warnings))))]
// TODO: Remove this when it's a hard error by default (error E0446).
// See Rust issue #34537 <https://github.com/rust-lang/rust/issues/34537>
#![deny(private_in_public)]

pub mod extractor;
pub mod handler;
pub mod helpers;
pub mod middleware;
pub mod pipeline;
pub mod prelude;
pub mod router;
pub mod service;
pub mod state;

/// Test utilities for Gotham and Gotham consumer apps.
#[cfg(feature = "testing")]
pub mod test;

/// Functions for creating a Gotham service using HTTP.
pub mod plain;

/// Functions for creating a Gotham service using HTTPS.
#[cfg(feature = "rustls")]
pub mod tls;

/// Re-export anyhow
pub use anyhow;
/// Re-export cookie
pub use cookie;
/// Re-export hyper
pub use hyper;
/// Re-export mime
pub use mime;

/// Re-export rustls
#[cfg(feature = "rustls")]
pub use tokio_rustls::rustls;

use futures_util::TryFutureExt;
use hyper::server::conn::Http;
use std::future::Future;
use std::io;
use std::net::ToSocketAddrs;
use std::sync::Arc;
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::{TcpListener, TcpStream};
use tokio::runtime::{self, Runtime};

use crate::handler::NewHandler;
use crate::service::GothamService;

pub use plain::*;
#[cfg(feature = "rustls")]
pub use tls::start as start_with_tls;

/// The error that can occur when starting the gotham server.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StartError {
    /// I/O error.
    #[error("I/O Error: {0}")]
    IoError(#[from] io::Error),
}

fn new_runtime(threads: usize) -> Runtime {
    runtime::Builder::new_multi_thread()
        .worker_threads(threads)
        .thread_name("gotham-worker")
        .enable_all()
        .build()
        .unwrap()
}

async fn tcp_listener<A>(addr: A) -> io::Result<TcpListener>
where
    A: ToSocketAddrs + 'static,
{
    let addr = addr.to_socket_addrs()?.next().ok_or_else(|| {
        io::Error::new(io::ErrorKind::Other, "unable to resolve listener address")
    })?;
    TcpListener::bind(addr).await
}

/// Returns a `Future` used to spawn a Gotham application.
///
/// This is used internally, but it's exposed for clients that want to set up their own TLS
/// support. The wrap argument is a function that will receive a tokio-io TcpStream and should wrap
/// the socket as necessary. Errors returned by this function will be ignored and the connection
/// will be dropped if the future returned by the wrapper resolves to an error.
pub async fn bind_server<'a, NH, F, Wrapped, Wrap>(
    listener: TcpListener,
    new_handler: NH,
    wrap: Wrap,
) -> !
where
    NH: NewHandler + 'static,
    F: Future<Output = Result<Wrapped, ()>> + Unpin + Send + 'static,
    Wrapped: Unpin + AsyncRead + AsyncWrite + Send + 'static,
    Wrap: Fn(TcpStream) -> F,
{
    let protocol = Arc::new(Http::new());
    let gotham_service = GothamService::new(new_handler);

    loop {
        let (socket, addr) = match listener.accept().await {
            Ok(ok) => ok,
            Err(err) => {
                log::error!("Socket Error: {}", err);
                continue;
            }
        };

        let service = gotham_service.connect(addr);
        let accepted_protocol = protocol.clone();
        let wrapper = wrap(socket);

        // NOTE: HTTP protocol errors and handshake errors are ignored here (i.e. so the socket
        // will be dropped).
        let task = async move {
            let socket = wrapper.await?;

            accepted_protocol
                .serve_connection(socket, service)
                .with_upgrades()
                .map_err(|_| ())
                .await?;

            Result::<_, ()>::Ok(())
        };

        tokio::spawn(task);
    }
}