Rust
Write a Coderunner Function, Job or Schedule in Rust.
Use this reference for Functions, Jobs and Schedules written in Rust. For a container with your own web server, see Services.
Project files
my-function/
├── handler.rs
└── Cargo.tomlZip these at the root of the archive, not inside a folder. Keep helper code in handler.rs, in inline mod blocks.
[package]
name = "serverless-runner"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"The handler
Export a public function named handler. Both arguments are &HashMap<String, String>:
payloadis the input: the request for a Function, the run's input for a Job.contextis reserved for information from the runtime. Don't rely on its contents yet.
Function example
A Function returns a HandlerResult:
use std::collections::HashMap;
pub struct HandlerResult {
pub status_code: u16,
pub headers: HashMap<String, String>,
pub body: String,
}
pub fn handler(
context: &HashMap<String, String>,
payload: &HashMap<String, String>,
) -> HandlerResult {
let mut headers = HashMap::new();
headers.insert("content-type".to_string(), "application/json".to_string());
match payload.get("name") {
Some(name) => HandlerResult {
status_code: 200,
headers,
body: serde_json::json!({ "greeting": format!("Hello, {name}") }).to_string(),
},
None => HandlerResult {
status_code: 400,
headers,
body: r#"{"error":"name is required"}"#.to_string(),
},
}
}Return an error result rather than panicking.
Job and Schedule example
A Job or Schedule returns () and writes its result as JSON to standard output:
use std::collections::HashMap;
pub fn handler(context: &HashMap<String, String>, payload: &HashMap<String, String>) {
eprintln!("Import started");
let count = import_customers(payload);
println!("{}", serde_json::json!({ "imported": count }));
}To report a panic as a failure message instead of crashing, wrap the body in std::panic::catch_unwind. Error handling is up to you; see Jobs.
Settings, secrets and logs
- Read settings with
std::env::var("NAME"). See Configuration and secrets. - Read secrets from the Secrets API at runtime, never from your ZIP; see Configuration and secrets.
- Output from
println!andeprintln!goes to the Process Log.
Deploy
gf deploy --name my-function --runtime rust --workload-type functionOr create the Coderunner in the Client Portal with Rust as its language and upload the ZIP; see Functions. If gf deploy doesn't accept rust, it lists the runtimes your workspace offers.