- main
- manifest
- deps
- main
- Install
- Run
use fastly::http::{header, StatusCode};
use fastly::{Error, Request, Response};
const BACKEND_NAME: &str = "origin_0";
const BUCKET_NAME: &str = "betts-gcp-gcs-fastly-tutorial";
#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
req.set_header(header::HOST, "storage.googleapis.com");
let mut retry_req = req.clone_with_body();
let path = req.get_path();
let page = if path.ends_with('/') {
"index.html"
} else {
""
};
let mut path_with_bucket = format!("/{}{}{}", BUCKET_NAME, path, page);
req.set_path(&path_with_bucket);
let resp = req.send(BACKEND_NAME)?;
if resp.get_status() == StatusCode::NOT_FOUND && !path_with_bucket.ends_with("/index.html") {
let orig_path = retry_req.get_path().to_string();
path_with_bucket = format!("/{}{}/index.html", BUCKET_NAME, &orig_path);
retry_req.set_path(&path_with_bucket);
let resp_retry = retry_req.send(BACKEND_NAME)?;
if resp_retry.get_status() == StatusCode::OK {
let new_location = format!("{}/", orig_path);
let resp_moved = Response::from_status(StatusCode::MOVED_PERMANENTLY)
.with_header(header::LOCATION, new_location);
Ok(resp_moved)
} else {
Ok(resp_retry)
}
} else {
Ok(resp)
}
}