aboutsummaryrefslogtreecommitdiffstats
path: root/rust/fatcat-api/examples/server.rs
blob: f9b8617cbbc777fccabefc842016bdafceb9d382 (plain)
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
//! Main binary entry point for fatcat implementation.

#![allow(missing_docs)]

// Imports required by this file.
// extern crate <name of this crate>;
extern crate clap;
extern crate fatcat;
extern crate hyper;
extern crate native_tls;
extern crate openssl;
extern crate swagger;
extern crate tokio_proto;
extern crate tokio_tls;

// Imports required by server library.
// extern crate fatcat;
// extern crate swagger;
extern crate chrono;
extern crate futures;
#[macro_use]
extern crate error_chain;

use clap::{App, Arg};
use hyper::server::Http;
use openssl::error::ErrorStack;
use openssl::ssl::{SslAcceptorBuilder, SslMethod};
use openssl::x509::X509_FILETYPE_PEM;
use swagger::auth::AllowAllAuthenticator;
use tokio_proto::TcpServer;

mod server_lib;

// Builds an SSL implementation for Simple HTTPS from some hard-coded file names
fn ssl() -> Result<SslAcceptorBuilder, ErrorStack> {
    let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?;

    // Server authentication
    ssl.set_private_key_file("examples/server-key.pem", X509_FILETYPE_PEM)?;
    ssl.set_certificate_chain_file("examples/server-chain.pem")?;
    ssl.check_private_key()?;

    Ok(ssl)
}

/// Create custom server, wire it to the autogenerated router,
/// and pass it to the web server.
fn main() {
    let matches = App::new("server")
        .arg(
            Arg::with_name("https")
                .long("https")
                .help("Whether to use HTTPS or not"),
        )
        .get_matches();

    let service_fn = fatcat::server::auth::NewService::new(AllowAllAuthenticator::new(
        server_lib::NewService,
        "cosmo",
    ));

    let addr = "127.0.0.1:8080"
        .parse()
        .expect("Failed to parse bind address");
    if matches.is_present("https") {
        let ssl = ssl().expect("Failed to load SSL keys");
        let builder: native_tls::TlsAcceptorBuilder =
            native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl);
        let tls_acceptor = builder.build().expect("Failed to build TLS acceptor");
        TcpServer::new(
            tokio_tls::proto::Server::new(Http::new(), tls_acceptor),
            addr,
        ).serve(service_fn);
    } else {
        // Using HTTP
        TcpServer::new(Http::new(), addr).serve(service_fn);
    }
}