Skip to content

Commit

Permalink
feat: Add proper example of configuring Rust functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
dejanb committed Jul 27, 2021
1 parent be1ae69 commit 695dda3
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 15 deletions.
2 changes: 1 addition & 1 deletion pkged.go

Large diffs are not rendered by default.

16 changes: 15 additions & 1 deletion templates/rust/events/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,20 @@ use actix_web::web;
/// ) -> Result<Event, actix_web::Error> {
/// Ok(Event::default())
/// }
pub fn configure(_cfg: &mut web::ServiceConfig) {
pub fn configure(cfg: &mut web::ServiceConfig) {
log::info!("Configuring service");
cfg.data(HandlerConfig::default());
}

/// An example of the function configuration structure.
pub struct HandlerConfig {
pub name: String,
}

impl Default for HandlerConfig {
fn default() -> HandlerConfig {
HandlerConfig {
name: String::from("world"),
}
}
}
13 changes: 9 additions & 4 deletions templates/rust/events/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use crate::config::HandlerConfig;
use actix_web::web;
use cloudevents::{event::Data, Event, EventBuilder, EventBuilderV10};
use log::info;
use serde_json::{from_slice, from_str, json};

// Implement your function's logic here
pub async fn handle(event: Event) -> Result<Event, actix_web::Error> {
pub async fn handle(
event: Event,
config: web::Data<HandlerConfig>,
) -> Result<Event, actix_web::Error> {
info!("event: {}", event);

let input = match event.data() {
Some(Data::Binary(v)) => from_slice(v)?,
Some(Data::String(v)) => from_str(v)?,
Some(Data::Json(v)) => v.to_owned(),
None => json!({ "name": "world" }),
None => json!({ "name": config.name }),
};

EventBuilderV10::from(event)
Expand All @@ -29,7 +34,7 @@ mod tests {
async fn valid_input() {
let mut input = Event::default();
input.set_data("application/json", json!({"name": "bootsy"}));
let resp = handle(input).await;
let resp = handle(input, web::Data::new(HandlerConfig::default())).await;
assert!(resp.is_ok());
match resp.unwrap().data() {
Some(Data::Json(output)) => assert_eq!("bootsy", output["hello"]),
Expand All @@ -39,7 +44,7 @@ mod tests {

#[actix_rt::test]
async fn no_input() {
let resp = handle(Event::default()).await;
let resp = handle(Event::default(), web::Data::new(HandlerConfig::default())).await;
assert!(resp.is_ok());
match resp.unwrap().data() {
Some(Data::Json(output)) => assert_eq!("world", output["hello"]),
Expand Down
17 changes: 16 additions & 1 deletion templates/rust/http/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,21 @@ use actix_web::web;
/// ) -> HttpResponse {
/// HttpResponse::NoContent()
/// }
pub fn configure(_cfg: &mut web::ServiceConfig) {
pub fn configure(cfg: &mut web::ServiceConfig) {
log::info!("Configuring service");
cfg.data(HandlerConfig::default());
}

/// An example of the function configuration structure.
#[derive(Clone)]
pub struct HandlerConfig {
pub name: String,
}

impl Default for HandlerConfig {
fn default() -> HandlerConfig {
HandlerConfig {
name: String::from("world"),
}
}
}
25 changes: 17 additions & 8 deletions templates/rust/http/src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use actix_web::{http::Method, HttpRequest, HttpResponse};
use crate::config::HandlerConfig;
use actix_web::{http::Method, web, HttpRequest, HttpResponse};
use log::info;

// Implement your function's logic here
pub async fn index(req: HttpRequest) -> HttpResponse {
pub async fn index(req: HttpRequest, config: web::Data<HandlerConfig>) -> HttpResponse {
info!("{:#?}", req);
if req.method() == Method::GET {
HttpResponse::Ok().body("Hello!\n")
HttpResponse::Ok().body(format!("Hello {}!\n", config.name))
} else {
HttpResponse::Ok().body("Thanks!\n")
HttpResponse::Ok().body(format!("Thanks {}!\n", config.name))
}
}

Expand All @@ -19,16 +20,24 @@ mod tests {
#[actix_rt::test]
async fn get() {
let req = test::TestRequest::get().to_http_request();
let resp = index(req).await;
let config = HandlerConfig::default();
let resp = index(req, web::Data::new(config.clone())).await;
assert_eq!(resp.status(), http::StatusCode::OK);
assert_eq!(&Body::from("Hello!\n"), resp.body().as_ref().unwrap());
assert_eq!(
&Body::from(format!("Hello {}!\n", config.name)),
resp.body().as_ref().unwrap()
);
}

#[actix_rt::test]
async fn post() {
let req = test::TestRequest::post().to_http_request();
let resp = index(req).await;
let config = HandlerConfig::default();
let resp = index(req, web::Data::new(config.clone())).await;
assert!(resp.status().is_success());
assert_eq!(&Body::from("Thanks!\n"), resp.body().as_ref().unwrap());
assert_eq!(
&Body::from(format!("Thanks {}!\n", config.name)),
resp.body().as_ref().unwrap()
);
}
}

0 comments on commit 695dda3

Please sign in to comment.