Chapter 3: Return something dynamic & Introduction to Akari

Getting the nunmer from the url

Starberry accepts dynamic url pattern, but how we are able to be benefited from this ability? Such as returning the number the user input after /test/

In some other frameworks, we may define something like this:

@app.url("/route/<number>") 
def number_function(number): 
    return render(number) 

Unfortunately, due to the support of Regex, starberry don’t allow you to define names for each part of the url.

You can only access the url through req.get_path(<int: The part of the url>)

Let’s change that function a little bit,

#[url(reg![&APP, LitUrl("test"), RegUrl("[0-9]+")])]  
async fn testnumber() -> HttpResponse { 
    text_response(req.get_path(1)) 
} 

This will get the second part of the url, which is the number part, in a text format.

Returning a Json or Template

Except for text, akari gives us the ability to return in Json or Templates.

We may use akari_template!() or akari_json!() to return them, below are 2 examples of how to do this

#[url(reg![&APP, LitUrl("test"), RegUrl("[0-9]+")])]  
async fn testnumber() -> HttpResponse { 
    akari_json!({ 
        number: req.get_path(1)
    }) // Return {number: ###} 
} 

OR

#[url(reg![&APP, LitUrl("test"), RegUrl("[0-9]+")])]  
async fn testnumber() -> HttpResponse { 
    akari_template!({
        "number.html":
        number=req.get_path(1)
    }) 
} 

Where you need to add a new file into template folder which is at the same level as the src folder,

<h1>-[ number ]-</h1> 

So that a header will render the number the user input

Akari Json and Introdcution to Akari Templates

With the build-in ability of reading json files and templating in akari, we can easily manipulate json and render dynamic templates

Akari json, officially akari object, can be constructed by using the object! macro. It is a json-like structure, and you are able to read and write data from it.

use akari::object; 
object!({
    number: 3, 
    string: "Hello", 
    array: [1, 2, 3], 
    object: { 
        a: 1, 
        b: 2, 
        c: 3 
    }
}) 

Then you can create a Json.

Where you can also use

use akari::object; 
use akari::Object; // Notice the capital O meaning that Object is a struct not macro 

let json = r#"{"key": "value", "number": 42, "list": [1, 2, 3]}"#; 
let obj = Object::from_json(json).expect("Failed to parse JSON"); 
let dir = "D://test/test.json"; 
Object::from_jsonf(dir).unwrap_or(Object::None); // Read a json from a file 
obj.into_jsonf(dir); // Write obj into the dir 

While various of methods are provided to read a value in json.

Be carefun about the difference between obj.to_string(), obj.string() and obj.into_json()

Akari template is a templating language, which wrap its syntax in -[ ... ]-. We will further discuss this in Chapter 9