Skip to content

Instantly share code, notes, and snippets.

@phamann
Created November 2, 2020 13:09
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 phamann/b1eddb67cae9d417e4da1ed61b9efe53 to your computer and use it in GitHub Desktop.
Save phamann/b1eddb67cae9d417e4da1ed61b9efe53 to your computer and use it in GitHub Desktop.
#[macro_use]
extern crate lazy_static;
use fastly::http::{Method, StatusCode};
use fastly::{
Body, Error, PendingRequest, Request, RequestBuilderExt, RequestExt, Response, ResponseExt,
};
use regex::Regex;
use std::convert::From;
lazy_static! {
static ref PATH_RE: Regex = Regex::new(r"^/uuid/([0-9]+)$").unwrap();
}
fn bad_request_response() -> Result<Response<Body>, Error> {
Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("Bad request"))?)
}
fn uuid_request_handler(req: Request<Body>) -> Result<Response<Body>, Error> {
let path_captures = PATH_RE
.captures(req.uri().path())
.ok_or(Error::msg("should have captures"))?;
let cap = path_captures.get(1);
match cap {
Some(raw_match) => {
let req_limit: i32 = raw_match.as_str().parse()?;
let reqs: Vec<PendingRequest> = (0..req_limit)
.map(|_| {
Request::builder()
.uri("https://httpbin.org/uuid")
.method(Method::GET)
.ttl(0)
.body(())
.unwrap()
.send_async("httpbin")
.unwrap()
})
.collect();
let resps: Vec<String> = reqs
.into_iter()
.map(|pr| {
pr.wait()
.map_or("".to_string(), |r| r.into_body().into_string())
})
.collect();
Ok(Response::builder()
.status(StatusCode::OK)
.body(Body::from(format!("[{}]", resps.join(","))))?)
}
None => {
eprintln!("No regex capture");
bad_request_response()
}
}
}
#[fastly::main]
fn main(req: Request<Body>) -> Result<impl ResponseExt, Error> {
match (req.method(), req.uri().path()) {
(&Method::GET, path) if PATH_RE.is_match(path) => match uuid_request_handler(req) {
Ok(r) => Ok(r),
Err(e) => {
eprintln!("Handler error: {}", e);
bad_request_response()
}
},
_ => Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("The page you requested could not be found"))?),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment