From 22975892fbbfb8a28fe9846bcd4387dda9125436 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20H=C3=A4drich?= <11225821+shaedrich@users.noreply.github.com> Date: Sun, 30 Jun 2024 14:57:49 +0200 Subject: [PATCH] [5/?] Add ability to run code examples in the playground: Add CORS exception for tutorial.ponylang.io to route /evaluate.json (#212) * Add CORS exception for tutorial.ponylang.io to rout /evaluate.json * Change let to const Co-authored-by: Joe Eli McIlvain * Add a type to layer * Formatting * Fix HeaderValue import Co-authored-by: Matthias Wahl * Add dependency Co-authored-by: Matthias Wahl As per https://github.com/ponylang/pony-playground/pull/212#pullrequestreview-2141020901 * Change const to let Co-authored-by: Matthias Wahl As per https://github.com/ponylang/pony-playground/pull/212#pullrequestreview-2141020901 * Move variable inside serve function Co-authored-by: Matthias Wahl As per https://github.com/ponylang/pony-playground/pull/212#discussion_r1654319376 --------- Co-authored-by: Joe Eli McIlvain Co-authored-by: Matthias Wahl --- Cargo.toml | 1 + src/api.rs | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a9117b5..a531019 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ serde_json = "1.0" tokio = { version = "1.38", features = ["full"] } wait-timeout = "0.2" url = { version = "2.5", "features" = ["serde"] } +tower-http = { version = "0.5", features = ["cors"] } [dev-dependencies] anyhow = "1.0" diff --git a/src/api.rs b/src/api.rs index 6c28cf3..672136b 100644 --- a/src/api.rs +++ b/src/api.rs @@ -6,10 +6,18 @@ use axum::{ use crate::routes::{compile, create_gist, evaluate, static_css, static_html, static_js}; use crate::GithubClient; +use axum::http::HeaderValue; use std::net::SocketAddr; +use tower_http::cors::CorsLayer; /// serve the api pub async fn serve(addr: SocketAddr, github_client: GithubClient) -> Result<()> { + let layer: CorsLayer = CorsLayer::new().allow_origin( + "https://tutorial.ponylang.io" + .parse::() + .unwrap(), + ); + let static_routes = Router::new() .route( "/web.css", @@ -24,11 +32,12 @@ pub async fn serve(addr: SocketAddr, github_client: GithubClient) -> Result<()> get(|| async { static_js(include_bytes!("../static/mode-pony.js")) }), ); let router = Router::new() + .route("/evaluate.json", post(evaluate)) + .layer(layer) // applies to every route() call before on `router` .route( "/", get(|| async { static_html(include_bytes!("../static/web.html")) }), ) - .route("/evaluate.json", post(evaluate)) .route("/compile.json", post(compile)) .route("/gist.json", post(create_gist)) .with_state(github_client)