Skip to content

Instantly share code, notes, and snippets.

@chrxr
Created September 5, 2017 02:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrxr/1f2b2c83101b8497e56a496650852849 to your computer and use it in GitHub Desktop.
Save chrxr/1f2b2c83101b8497e56a496650852849 to your computer and use it in GitHub Desktop.
Successfully getting a string from request.body, but not the way I want to
extern crate hyper;
extern crate futures;
extern crate unicase;
extern crate tokio_core;
use hyper::header::{Headers, ContentLength, AccessControlAllowOrigin, AccessControlAllowHeaders};
use hyper::Body;
use hyper::server::{Http, Request, Response, Service};
use std::process::Command;
use std::ascii::AsciiExt;
use std::str;
use futures::Stream;
use futures::stream::Map;
use futures::future::*;
use hyper::Chunk;
use unicase::Ascii;
use std::io;
struct HelloWorld;
const PHRASE: &'static str = "Hello, World!";
impl Service for HelloWorld {
type Request = Request;
type Error = hyper::Error;
type Response = Response<Map<Body, fn(Chunk) -> Chunk>>;
type Future = futures::future::FutureResult<Self::Response, Self::Error>;
fn call(&self, _req: Request) -> Self::Future {
// let mut child = Command::new("sleep").arg("5").spawn().unwrap();
// let _result = child.wait().unwrap();
let mut response = Response::new();
let mut headers = Headers::new();
let mut ContentType = Ascii::new("Content-Type".to_owned());
let mut AccessControlAH = Ascii::new("Access-Control-Allow-Headers".to_owned());
headers.set(AccessControlAllowHeaders(vec![ContentType, AccessControlAH]));
headers.set(AccessControlAllowOrigin::Any);
response.set_body(_req.body().map(to_uppercase as _));
futures::future::ok(response
.with_headers(headers)
)
}
}
fn to_uppercase(chunk: Chunk) -> Chunk {
let uppered = chunk.iter()
.map(|byte| byte.to_ascii_uppercase())
.collect::<Vec<u8>>();
let uppered_copy = uppered.clone();
let mut utf8_vec = &uppered_copy[..];
let s = match str::from_utf8(&utf8_vec) {
Ok(v) => v,
Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
};
let stringified = String::from(s);
println!("{}", stringified);
Chunk::from(uppered)
}
fn main() {
let addr = "0.0.0.0:3000".parse().unwrap();
let server = Http::new().bind(&addr, || Ok(HelloWorld)).unwrap();
server.run().unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment