- main
- manifest
- deps
- main
- Install
- Run
use fastly::http::{HeaderValue, StatusCode};
use fastly::{Request, Response, Error};
use url::Url;
use std::str::from_utf8;
use percent_encoding::percent_decode;
#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
let url_param = match req.get_query_parameter("url") {
Some(param) => param,
None => {
return Ok(Response::new()
.with_status(StatusCode::BAD_REQUEST)
.with_body_text_html("Missing `url` query parameter"));
}
};
let decoded_bytes = percent_decode(&url_param.as_bytes()).decode_utf8().unwrap();
let decoded_str = match from_utf8(&decoded_bytes.as_bytes()) {
Ok(str) => str,
Err(_) => panic!("Failed to convert decoded bytes to UTF-8 string"),
};
let decoded_url = match Url::parse(decoded_str) {
Ok(url) => url,
Err(_) => panic!("unable to parse a valid url from query string"),
};
let domain = decoded_url.host().map(|h| h.to_string()).unwrap();
if !is_valid_domain(&domain) {
return Ok(Response::new()
.with_status(StatusCode::FORBIDDEN)
.with_body_text_html("Invalid domain"));
}
Ok(Response::new()
.with_status(StatusCode::OK)
.with_header("Content-Type", HeaderValue::from_static("text/plain"))
.with_body_text_html("hello"))
}
fn valid_domains() -> Vec<&'static str> {
vec!["example.com", "fastly.com"]
}
fn is_valid_domain(domain: &str) -> bool {
valid_domains().contains(&domain)
}