Tiny HTTP: generate dynamic response, show the current time ⏰

tiny_http web chrono UTC Local date time HTML

Part of the Tiny HTTP series. Previously we saw how to show static HTML content now let's go a tiny step further and show how to display dynamic content. Every time the user access the page we'll show the current time as it is available on the server.

For this we are going to use the chrono crate.

First let's see the dependencies in the Cargo.toml file:

examples/tiny-http/show-time/Cargo.toml

[package]
name = "show-time"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ascii = "1.1"
chrono = "0.4"
tiny_http = "0.12"

The new code

First we load the tools we are going to use:

use chrono::{DateTime, Local, Utc};

Then we fetch the UTC time and the localtime. Finally we create an HTML string.

let utc: DateTime<Utc> = Utc::now();
let local: DateTime<Local> = Local::now();
let html = format!("<table><tr><td>UTC: </td><td>{}</td></tr><tr><td>Localtime: </td><td>{}</td></tr></table>", utc, local);

The Full source code

examples/tiny-http/show-time/src/main.rs

use ascii::AsciiString;
use chrono::{DateTime, Local, Utc};
use std::str::FromStr;
use tiny_http::{Header, HeaderField, Response, Server};

fn main() {
    let host = "127.0.0.1";
    let port = "5000";

    let server_str = format!("{}:{}", host, port);

    let server = Server::http(&server_str).expect("Failed to start demo server.");

    for request in server.incoming_requests() {
        let header = Header {
            field: HeaderField::from_str("Content-type").unwrap(),
            value: AsciiString::from_ascii("text/html").unwrap(),
        };
        let utc: DateTime<Utc> = Utc::now();
        let local: DateTime<Local> = Local::now();
        let html = format!("<table><tr><td>UTC: </td><td>{}</td></tr><tr><td>Localtime: </td><td>{}</td></tr></table>", utc, local);
        request
            .respond(Response::from_string(html).with_header(header))
            .unwrap();
    }
}

Related Pages

Getting started with Tiny HTTP building a web application in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo