Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CORS headers #53

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 22 additions & 25 deletions image-api-classify/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@ async fn classify(req: Request<Body>) -> Result<Response<Body>, anyhow::Error> {
let labels = include_str!("models/mobilenet_v1_1.0_224/labels_mobilenet_quant_v1_224.txt");
match (req.method(), req.uri().path()) {
// Serve some instructions at /
(&Method::GET, "/") => Ok(Response::new(Body::from(
"Try POSTing data to /classify such as: `curl http://localhost:9006/classify -X POST --data-binary '@grace_hopper.jpg'`",
))),
(&Method::GET, "/") => Ok(response_build(
&String::from("Try POSTing data to /classify such as: `curl http://localhost:9006/classify -X POST --data-binary '@grace_hopper.jpg'`")
)),

// CORS Options
(&Method::OPTIONS, "/classify") => Ok(response_build(&String::from(""))),

(&Method::POST, "/classify") => {
let headers = req.headers().to_owned();
Expand Down Expand Up @@ -59,20 +62,20 @@ async fn classify(req: Request<Body>) -> Result<Response<Body>, anyhow::Error> {
let client = dapr::Dapr::new(3504);
let ts = Utc::now().timestamp_millis();

let kvs = json!({
"event_ts": ts,
"op_type": "classify",
"input_size": buf.len()
let kvs = json!({
"event_ts": ts,
"op_type": "classify",
"input_size": buf.len()
});
client.invoke_service("events-service", "create_event", kvs).await?;

let kvs = json!([{
let kvs = json!([{
"key": ip, "value": ts
}]);
println!("KVS is {}", serde_json::to_string(&kvs)?);
client.save_state("statestore", kvs).await?;

Ok(Response::new(Body::from(format!("{} is detected with {}/255 confidence", class_name, max_value))))
Ok(response_build(&format!("{} is detected with {}/255 confidence", class_name, max_value)))
}

// Return the 404 Not Found for other routes.
Expand All @@ -84,6 +87,16 @@ async fn classify(req: Request<Body>) -> Result<Response<Body>, anyhow::Error> {
}
}

// CORS headers
fn response_build(body: &String) -> Response<Body> {
Response::builder()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
.header("Access-Control-Allow-Headers", "api,Keep-Alive,User-Agent,Content-Type")
.body(Body::from(body.to_string()))
.unwrap()
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr = SocketAddr::from(([0, 0, 0, 0], 9006));
Expand All @@ -99,20 +112,4 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
eprintln!("server error: {}", e);
}
Ok(())

/*
let addr = SocketAddr::from(([0, 0, 0, 0], 9006));

let listener = TcpListener::bind(addr).await?;
println!("Listening on http://{}", addr);
loop {
let (stream, _) = listener.accept().await?;

tokio::task::spawn(async move {
if let Err(err) = Http::new().serve_connection(stream, service_fn(classify)).await {
println!("Error serving connection: {:?}", err);
}
});
}
*/
}
33 changes: 21 additions & 12 deletions image-api-grayscale/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ async fn grayscale(req: Request<Body>) -> Result<Response<Body>, anyhow::Error>
"Try POSTing data to /grayscale such as: `curl http://localhost:9005/grayscale -X POST --data-binary '@my_img.png'`",
))),

// CORS Options
(&Method::OPTIONS, "/grayscale") => Ok(response_build(&String::from(""), "text/html")),

(&Method::POST, "/grayscale") => {
let headers = req.headers().to_owned();
let mut ip = "0.0.0.0";
Expand Down Expand Up @@ -43,31 +46,26 @@ async fn grayscale(req: Request<Body>) -> Result<Response<Body>, anyhow::Error>
filtered.write_to(&mut buf, ImageOutputFormat::Png).unwrap();
}
};

let res = base64::encode(&buf);
let response = Response::builder()
.header("Content-Type", "image/png")
.body(Body::from(res))
.unwrap();

// Connect to the attached sidecar
let client = dapr::Dapr::new(3503);
let ts = Utc::now().timestamp_millis();

let kvs = json!({
"event_ts": ts,
"op_type": "grayscale",
"input_size": image_data.len()
let kvs = json!({
"event_ts": ts,
"op_type": "grayscale",
"input_size": image_data.len()
});
client.invoke_service("events-service", "create_event", kvs).await?;

let kvs = json!([{
let kvs = json!([{
"key": ip, "value": ts
}]);
println!("KVS is {}", serde_json::to_string(&kvs)?);
client.save_state("statestore", kvs).await?;

Ok(response)
let res = base64::encode(&buf);
Ok(response_build(&res, "image/png"))
}

// Return the 404 Not Found for other routes.
Expand All @@ -79,6 +77,17 @@ async fn grayscale(req: Request<Body>) -> Result<Response<Body>, anyhow::Error>
}
}

// CORS headers
fn response_build(body: &String, content_type: &str) -> Response<Body> {
Response::builder()
.header("Content-Type", content_type)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
.header("Access-Control-Allow-Headers", "api,Keep-Alive,User-Agent,Content-Type")
.body(Body::from(body.to_string()))
.unwrap()
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr = SocketAddr::from(([0, 0, 0, 0], 9005));
Expand Down