Skip to main content

hello_http/
hello_http.rs

1use keket::{
2    database::{AssetDatabase, path::AssetPath},
3    fetch::{AssetAwaitsAsyncFetch, deferred::DeferredAssetFetch},
4    protocol::{bundle::BundleAssetProtocol, bytes::BytesAssetProtocol, text::TextAssetProtocol},
5};
6use keket_http::{HttpAssetFetch, third_party::reqwest::Url};
7use serde_json::Value;
8use std::error::Error;
9
10fn main() -> Result<(), Box<dyn Error>> {
11    /* ANCHOR: main */
12    let mut database = AssetDatabase::default()
13        .with_protocol(TextAssetProtocol)
14        .with_protocol(BytesAssetProtocol)
15        .with_protocol(BundleAssetProtocol::new("json", |bytes: Vec<u8>| {
16            Ok((serde_json::from_slice::<Value>(&bytes)?,).into())
17        }))
18        // HTTP asset fetch with root URL for assets.
19        .with_fetch(DeferredAssetFetch::new(HttpAssetFetch::new(
20            "https://raw.githubusercontent.com/PsichiX/Keket/refs/heads/master/resources/",
21        )?));
22
23    // Ensure assets exists or start getting fetched.
24    let lorem = database.ensure("text://lorem.txt")?;
25    let json = database.ensure("json://person.json")?;
26    let trash = database.ensure("bytes://trash.bin")?;
27
28    // Wait while database is busy.
29    while database.is_busy() {
30        println!("Waiting for database to be free");
31        println!(
32            "Loading:\n- Lorem Ipsum: {}\n- JSON: {}\n- Bytes: {}",
33            lorem.has::<AssetAwaitsAsyncFetch>(&database),
34            json.has::<AssetAwaitsAsyncFetch>(&database),
35            trash.has::<AssetAwaitsAsyncFetch>(&database)
36        );
37        database.maintain()?;
38    }
39
40    println!("Lorem Ipsum: {}", lorem.access::<&String>(&database));
41    println!("JSON: {:#}", json.access::<&Value>(&database));
42    println!("Bytes: {:?}", trash.access::<&Vec<u8>>(&database));
43
44    // List all assets from HTTP.
45    for (asset_path, url) in database.storage.query::<true, (&AssetPath, &Url)>() {
46        println!("Asset: `{asset_path}` at url: `{url}`");
47    }
48    /* ANCHOR_END: main */
49
50    Ok(())
51}