Enabling the feature
While support is still experimental, support for rust server less functions must be enabled on a per-site basis. You can enable rust support by enabling this environment variable
netlify env:set NETLIFY_EXPERIMENTAL_BUILD_RUST_SOURCE true
Creating a serverless function
In order to create a new rust function use cargo to initialize a new project
cargo init FUNCTION_NAME
The name you choose for the function determines its endpoint. For example, running cargo init hello will create a function which, when deployed, will be accessible on the /.netlify/functions/hello endpoint.
Alternatively, you can get a jump-start with the Netlify CLI ’s function generator. Run netlify functions:create —language=rust, choose a template, and you’ll get a fully working function, ready to be deployed and modified to fit your needs.
Structure
use aws_lambda_events::event::apigw::{ApiGatewayProxyRequest, ApiGatewayProxyResponse};
use aws_lambda_events::encodings::Body;
use http::header::HeaderMap;
use lambda_runtime::{handler_fn, Context, Error};
use log::LevelFilter;
use simple_logger::SimpleLogger;
#[tokio::main]
async fn main() -> Result<(), Error> {
SimpleLogger::new().with_level(LevelFilter::Info).init().unwrap();
let func = handler_fn(my_handler);
lambda_runtime::run(func).await?;
Ok(())
}
pub(crate) async fn my_handler(event: ApiGatewayProxyRequest, _ctx: Context) -> Result<ApiGatewayProxyResponse, Error> {
let path = event.path.unwrap();
let resp = ApiGatewayProxyResponse {
status_code: 200,
headers: HeaderMap::new(),
multi_value_headers: HeaderMap::new(),
body: Some(Body::Text("Hello world".to_owned())),
is_base64_encoded: Some(false),
};
Ok(resp)
}
Links
- https://www.netlify.com/blog/2021/10/14/write-netlify-functions-in-rust/
- https://docs.netlify.com/configure-builds/manage-dependencies/#rust
- https://www.christopherbiscardi.com/deploy-your-first-netlify-serverless-function-powered-by-rust