Skip to content

Instantly share code, notes, and snippets.

@olehermanse
Created March 30, 2019 19:13
Show Gist options
  • Save olehermanse/466536821b15b38849c830ee450caf5f to your computer and use it in GitHub Desktop.
Save olehermanse/466536821b15b38849c830ee450caf5f to your computer and use it in GitHub Desktop.
Rust Hyper server with shared immutable access to file
extern crate hyper;
use std::fs::File;
use std::io::prelude::*;
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
use hyper::rt::{self, Future};
fn get_html() -> std::io::Result<(String)> {
let mut file = File::open("web/index.html")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
return Ok(contents);
}
fn main() {
let addr = ([127, 0, 0, 1], 3000).into();
// How can I move the get_html call here?
let new_service = move || {
service_fn_ok(|_| {
let content = get_html().unwrap();
Response::new(Body::from(content))
})
};
let server = Server::bind(&addr)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
rt::run(server);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment