Skip to content

Writing a Backend Service in Rust

Prerequisites

Connecting to the Message Bus

use nats::asynk::Connection;
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let nc = Connection::new("nats://localhost:4222").await?;
    let sub = nc.subscribe("bar")?.with_handler(move |msg| {
        println!("Received {}", &msg);
        Ok(())
    });

    Ok(())
}

Getting configuration from the environment

[dependencies]
dotenv = "0.15.0"
use dotenv::dotenv;
use std::env;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    dotenv().ok();

    let nats_url = env::var("NATS_URL")?;
    let nc = Connection::new(nats_url).await?;

    Ok(())
}