I'm trying to learn Rust, I've decided to start working on a simple API using Actix.
What I did was create a root endpoint that would return some basic info about the app (name, version, uptime).
Trying to generate current uptime is giving me a headache. At first I tried to create a constant, but I found out I cannot call non-const fn SystemTime::now in constants calls
. After doing some research I found out I should be using Lazy to solve this problem.
This fixed the compile issue, but the problem now is that the uptime
value is always 0. I'm guessing the reason for this is that Lazy always executes this method when called, which I do not want. How do I solve this?
This is my current implementation, essentially I want STARTUP_TIME
to be initialized on app startup:
use actix_web::{get, HttpResponse, Responder};
use once_cell::sync::Lazy;
use serde::{Serialize};
#[derive(Serialize)]
pub struct Hello {
pub name: String,
pub uptime: u64,
pub version: String,
}
const STARTUP_TIME: Lazy<std::time::SystemTime> = Lazy::new(|| std::time::SystemTime::now());
#[get("/")]
async fn hello() -> impl Responder {
let startup_time = *STARTUP_TIME;
let uptime = std::time::SystemTime::now()
.duration_since(startup_time)
.unwrap()
.as_secs();
let hello = Hello {
name: env!("CARGO_PKG_NAME").to_string(),
uptime,
version: env!("CARGO_PKG_VERSION").to_string(),
};
HttpResponse::Ok().json(hello)
}