<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Davide Ferrero on Medium]]></title>
        <description><![CDATA[Stories by Davide Ferrero on Medium]]></description>
        <link>https://medium.com/@deid84?source=rss-98c59e5e0a43------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hVBQ5JePa5_0WysD_fpbJA.jpeg</url>
            <title>Stories by Davide Ferrero on Medium</title>
            <link>https://medium.com/@deid84?source=rss-98c59e5e0a43------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:52:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deid84/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Rust’s Safety Features in Cpp: RAII]]></title>
            <link>https://medium.com/codex/implementing-rusts-safety-features-in-cpp-raii-85b9c29f8930?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b9c29f8930</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 07:02:42 GMT</pubDate>
            <atom:updated>2024-07-04T11:16:56.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tc-w7aoUC4MjtIzZ" /><figcaption>Photo by <a href="https://unsplash.com/@dtopkin1?utm_source=medium&amp;utm_medium=referral">Dayne Topkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the previous article, we began analyzing a series of best practices for using <strong>C++</strong> with a level of safety as close as possible to what is offered by <strong>Rust</strong>. Specifically, we started with a simple example related to memory management and how various elements in the latest versions contribute to helping us in this regard. Today, we will tackle another topic, particularly related to <strong>C++</strong>, but actually applicable to other programming languages as well: <strong>RAII</strong>.</p><p><strong>RAII</strong> <em>(Resource Acquisition Is Initialization)</em> is a programming principle in <strong>C++</strong> that associates resource management with objects whose lifespan is defined by the object’s lifetime. This principle is used to ensure that resources such as memory, files, and semaphores are correctly allocated and released. <strong>RAII</strong> is based on the concept that resource acquisition should occur during an object’s initialization, and resource release should occur during the object’s destruction.</p><h3>Key Concepts of RAII</h3><ol><li><strong>Constructor:</strong> Allocates and acquires resources.</li><li><strong>Destructor:</strong> Releases and deallocates resources.</li></ol><h3>RAII Example</h3><p>Let’s consider a simple example that uses RAII to manage dynamic memory.</p><pre>#include &lt;iostream&gt;<br><br>class Resource {<br>public:<br>    Resource() {<br>        // Resource acquisition (e.g., memory allocation)<br>        data = new int[100]; // Let&#39;s assume it is an expensive resource<br>        std::cout &lt;&lt; &quot;Resource acquired&quot; &lt;&lt; std::endl;<br>    }<br><br>    ~Resource() {<br>        // Resource release<br>        delete[] data;<br>        std::cout &lt;&lt; &quot;Resource released&quot; &lt;&lt; std::endl;<br>    }<br><br>private:<br>    int* data;<br>};<br><br>void useResource() {<br>    Resource res;<br>    // Resource use<br>}<br><br>int main() {<br>    useResource();<br>    // When useResource finishes, the destructor of Resource is called automatically<br>    return 0;<br>}</pre><p>In this example:</p><ul><li>The resource (dynamic memory) is acquired in the constructor of the Resource class.</li><li>The resource is released in the destructor of the Resource class.</li><li>When the object res goes out of scope (when useResource finishes), the destructor is called automatically, correctly releasing the memory.</li></ul><h3>RAII Advantages</h3><ol><li><strong>Automatic Resource Management:</strong> Associates the lifespan of the resource with the lifespan of the object, eliminating the need to manually manage resource acquisition and release.</li><li><strong>Exceptions and Safety:</strong> If an exception is thrown, the destructor will still be automatically called when the object goes out of scope, ensuring that resources are properly released.</li><li><strong>Readability and Maintainability:</strong> The code is more readable and maintainable because resource management is confined to the constructor and destructor.</li></ol><h3>RAII with Smart Pointers</h3><p>In C++, smart pointers (e.g., std::unique_ptr and std::shared_ptr) implement the concept of RAII for managing dynamic memory.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>void useResource() {<br>    std::unique_ptr&lt;int[]&gt; data(new int[100]);<br>    // Use of the resource<br>}<br><br>int main() {<br>    useResource();<br>    // When useResource finishes, allocated memory is automatically deallocated<br>    return 0;<br>}</pre><p>In this example:</p><ul><li>std::unique_ptr automatically manages the allocated memory.</li><li>When data goes out of scope, the memory is deallocated automatically.</li></ul><h3>RAII with File I/O</h3><p>Another common example is file management.</p><pre>#include &lt;iostream&gt;<br>#include &lt;fstream&gt;<br><br>class File {<br>public:<br>    // Constructor opens the file<br>    File(const std::string&amp; filename) {<br>        file.open(filename);<br>        if (!file.is_open()) {<br>            throw std::runtime_error(&quot;Failed to open file&quot;);<br>        }<br>    }<br><br>    // Destructor closes the file<br>    ~File() {<br>        if (file.is_open()) {<br>            file.close();<br>        }<br>    }<br><br>    // Other methods to operate on the file<br><br>private:<br>    std::fstream file;<br>};<br><br>void useFile() {<br>    File file(&quot;example.txt&quot;);<br>    // File usage<br>}<br><br>int main() {<br>    try {<br>        useFile();<br>    } catch (const std::exception&amp; e) {<br>        std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;<br>    }<br>    // When useFile finishes, the File destructor will automatically close the file<br>    return 0;<br>}</pre><p>In this example:</p><ul><li>The file is opened in the constructor and closed in the destructor.</li><li>If the file cannot be opened, an exception is thrown.</li><li>The file is automatically closed when the File object goes out of scope, ensuring that resources are released properly.</li></ul><h3>Conclusion</h3><p>The RAII principle is fundamental in C++ for safe and automatic resource management. By associating resource acquisition and release with the object’s lifecycle, RAII significantly reduces the risk of memory leaks, ensures that resources are always released properly, and simplifies resource management, especially in the presence of exceptions. Using RAII, along with the smart pointers provided by the C++ Standard Library, is a recommended practice for writing robust and secure C++ code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b9c29f8930" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/implementing-rusts-safety-features-in-cpp-raii-85b9c29f8930">Implementing Rust’s Safety Features in Cpp: RAII</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Rust’s Safety Features in Cpp: Memory Management]]></title>
            <link>https://medium.com/codex/implementing-rusts-safety-features-in-cpp-memory-management-42113ec22405?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/42113ec22405</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[safety]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 07:02:45 GMT</pubDate>
            <atom:updated>2024-06-27T10:08:46.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iIR8rXQ30dXhkPe6" /><figcaption>Photo by <a href="https://unsplash.com/@joetography?utm_source=medium&amp;utm_medium=referral">Joe Dudeck</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In recent years, <strong>Rust</strong> has experienced exponential growth in terms of popularity. Its blend of performance, language expressiveness, and modernity has made it the most appreciated language by developers, according to <a href="https://survey.stackoverflow.co/2023/#section-admired-and-desired-programming-scripting-and-markup-languages">Stack Overflow’s</a> annual ranking. However, despite my own enjoyment in using it, we must ensure that the hype surrounding this language does not distort reality.</p><p>Increasingly, I hear claims that <strong>Rust</strong> will supplant more widely-used languages, particularly <strong>C++</strong>, which I personally do not agree with. While it is true that Rust was born with safety as a top priority, it is also true that C++, especially with standards from version 11 onwards, has greatly improved in many aspects that in recent years seem exclusively associated with Rust. This misconception arises because, in terms of market presence and capabilities, C++ is anything but on the verge of obsolescence. In this and upcoming articles, I will attempt to illustrate why with some examples.</p><h3>Dynamic Memory Management: Using Smart Pointers Instead of ‘new’ and &#39;delete&#39;</h3><p>In C++, dynamic memory management is crucial for writing safe and efficient code. Improper use of new and delete can lead to memory leaks, dangling pointers, and other issues. Fortunately, modern C++ provides alternatives such as unique_ptr and shared_ptr that simplify memory management and reduce the risk of errors.</p><h4>Usage of new and delete</h4><p>The traditional way to allocate dynamic memory in C++ is to use new to allocate memory and delete to deallocate it. However, this practice can be error-prone if not handled carefully.</p><p><strong>Example of usage of </strong><strong>new and </strong><strong>delete:</strong></p><pre>#include &lt;iostream&gt;<br><br>void traditionalMemoryManagement() {<br>    // Memory allocation<br>    int* p = new int(42);<br>    std::cout &lt;&lt; &quot;Valore: &quot; &lt;&lt; *p &lt;&lt; std::endl;<br><br>    // Memory deallocation<br>    delete p;<br>}</pre><p>In this example, new int(42) dynamically allocates an integer, and delete p deallocates the memory. However, if we forget to call delete, a memory leak occurs.</p><p><strong>Common issues:</strong></p><ul><li><strong>Memory leaks:</strong> If you forget to call delete, memory is not released.</li><li><strong>Dangling pointers:</strong> Accessing a pointer after calling delete can cause the program to behave unpredictably.</li></ul><h4>Usage of unique_ptr</h4><p>std::unique_ptr is a smart pointer that owns an object and ensures that the object is deallocated when the unique_ptrgoes out of scope. It cannot be copied, only moved, which prevents accidental duplications.</p><p><strong>Example of usage of </strong><strong>unique_ptr:</strong></p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>void useUniquePtr() {<br>    // Memory allocation with unique_ptr<br>    std::unique_ptr&lt;int&gt; p = std::make_unique&lt;int&gt;(42);<br>    std::cout &lt;&lt; &quot;Valore: &quot; &lt;&lt; *p &lt;&lt; std::endl;<br>    // Memory automatically deallocated when p goes out of scope<br>}</pre><p><strong>Advantages:</strong></p><ul><li>You don’t need to manually call delete.</li><li>It prevents memory leaks and dangling pointers.</li><li>It cannot be copied, reducing the risk of ownership duplication.</li></ul><h4>Usage of shared_ptr</h4><p>std::shared_ptr is a smart pointer that allows sharing ownership of an object among multiple pointers. The memory is deallocated when the last shared_ptr owning the object is destroyed.</p><p><strong>Example of usage of </strong><strong>shared_ptr:</strong></p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>void useSharedPtr() {<br>    // Memory allocation with shared_ptr<br>    std::shared_ptr&lt;int&gt; p1 = std::make_shared&lt;int&gt;(42);<br>    {<br>        std::shared_ptr&lt;int&gt; p2 = p1; // Property sharing<br>        std::cout &lt;&lt; &quot;Valore: &quot; &lt;&lt; *p2 &lt;&lt; std::endl;<br>    } // p2 out of scope, but someone else still using it<br><br>    std::cout &lt;&lt; &quot;Valore: &quot; &lt;&lt; *p1 &lt;&lt; std::endl;<br>    // All pointers gone out of scope, memory automatically deallocated<br>}</pre><p><strong>Advantages:</strong></p><ul><li>Automatic management of shared memory.</li><li>Memory is deallocated only when the last shared_ptr owning the object is destroyed.</li><li>More flexible than unique_ptr when shared ownership is needed.</li></ul><h3>Conclusions</h3><p>Switching from using new and delete to smart pointers like unique_ptr and shared_ptr can significantly improve the security and robustness of C++ code. Smart pointers reduce the risk of memory leaks, dangling pointers, and other common memory management errors, while simplifying the writing of safe and efficient code. This is just one of many examples that we will analyze to demonstrate how C++ lacks nothing in terms of security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42113ec22405" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/implementing-rusts-safety-features-in-cpp-memory-management-42113ec22405">Implementing Rust’s Safety Features in Cpp: Memory Management</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customize error handling with thiserror]]></title>
            <link>https://levelup.gitconnected.com/customize-error-handling-with-thiserror-bb4b382e389e?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4b382e389e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 14:45:47 GMT</pubDate>
            <atom:updated>2024-06-20T14:45:47.836Z</atom:updated>
            <content:encoded><![CDATA[<h2>Improve error handling with thiserror</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7q75RhhDpFg9VUDQwd_eQ@2x.jpeg" /><figcaption>Photo by Brett Jordan on Unsplash</figcaption></figure><p>One of the first articles I wrote on this platform was dedicated to the <a href="https://medium.com/gitconnected/simplify-rust-error-handling-with-anyhow-f680410e70f9">anyhow</a> crate. In simple terms, it is a wrapper for Box&lt;dyn Error&gt;, which allows us to easily use the result unwrapping system with the question mark operator (?). However, this simplification is very useful when writing the final application but is not recommended for use when writing public APIs for a library.</p><p>Therefore, if we are building our own library or driver, the thiserror crate can be a valuable tool. The thiserror crate in Rust is used to simplify the definition of custom error types. It provides a convenient and concise way to implement the std::error::Error trait for error types, improving code readability and maintainability.</p><h3>Advantages of thiserror</h3><ul><li><strong>Concise Syntax</strong>: thiserror uses derive macros to reduce the boilerplate code needed to define and implement error types.</li><li><strong>Custom Error Messages</strong>: It allows specifying custom error messages easily.</li><li><strong>Easy Conversions</strong>: Facilitates conversion between different error types.</li><li><strong>Integration with </strong><strong>std::error::Error</strong>: Automatically implements the methods required by the std::error::Error trait.</li></ul><p>Almost always, when writing a library, you’ll use other crates to model your work. From personal experience, this is where thiserror offers the greatest benefits.</p><p>Suppose we have a library that uses several other libraries, each with its own error types: std::io::Error, serde_json::Error, and reqwest::Error. With thiserror, we can create a central error type that can encapsulate and represent all these errors.</p><pre>use thiserror::Error;<br><br>#[derive(Error, Debug)]<br>pub enum MyLibError {<br>    #[error(&quot;IO error&quot;)]<br>    Io(#[from] std::io::Error),<br><br>    #[error(&quot;JSON serialization error&quot;)]<br>    SerdeJson(#[from] serde_json::Error),<br><br>    #[error(&quot;HTTP request error&quot;)]<br>    Reqwest(#[from] reqwest::Error),<br><br>    #[error(&quot;an unknown error occurred&quot;)]<br>    Unknown,<br>}</pre><p>With this enum, we have centralized all the error types that various crates might generate within our library. Once the various possibilities are defined, we can use our MyLibError within our library.</p><pre>use reqwest;<br>use serde_json;<br>use std::fs::File;<br>use std::io::Read;<br><br>fn perform_io_operation() -&gt; Result&lt;String, MyLibError&gt; {<br>    let mut file = File::open(&quot;example.txt&quot;)?;<br>    let mut contents = String::new();<br>    file.read_to_string(&amp;mut contents)?;<br>    Ok(contents)<br>}<br><br>fn parse_json(data: &amp;str) -&gt; Result&lt;serde_json::Value, MyLibError&gt; {<br>    let parsed: serde_json::Value = serde_json::from_str(data)?;<br>    Ok(parsed)<br>}<br><br>fn make_http_request(url: &amp;str) -&gt; Result&lt;String, MyLibError&gt; {<br>    let response = reqwest::blocking::get(url)?.text()?;<br>    Ok(response)<br>}<br><br>fn main() {<br>    match perform_io_operation() {<br>        Ok(contents) =&gt; println!(&quot;File contents: {}&quot;, contents),<br>        Err(e) =&gt; println!(&quot;Failed to perform IO operation: {}&quot;, e),<br>    }<br><br>    let json_data = r#&quot;{&quot;key&quot;: &quot;value&quot;}&quot;#;<br>    match parse_json(json_data) {<br>        Ok(parsed) =&gt; println!(&quot;Parsed JSON: {}&quot;, parsed),<br>        Err(e) =&gt; println!(&quot;Failed to parse JSON: {}&quot;, e),<br>    }<br><br>    let url = &quot;https://www.rust-lang.org&quot;;<br>    match make_http_request(url) {<br>        Ok(body) =&gt; println!(&quot;HTTP response body: {}&quot;, body),<br>        Err(e) =&gt; println!(&quot;Failed to make HTTP request: {}&quot;, e),<br>    }<br>}</pre><p>We can summarize what we’ve done in the following points:</p><ol><li><strong>Error Type Definition</strong>: The #[derive(Error, Debug)] macro is used to derive the implementations of the Error and Debug traits. Each variant of the MyLibError enum represents a different error type from the libraries used.</li><li><strong>Automatic Error Conversion</strong>: The #[from] attribute on each variant allows for automatic conversion from the original error types to the central error type MyLibError. This makes the code using these functions much simpler and cleaner.</li><li><strong>Library Functions</strong>: The functions perform_io_operation, parse_json, and make_http_request demonstrate how to propagate different error types using the central error type MyLibError.</li></ol><h4>Advantages:</h4><ol><li><strong>Consistency</strong>: A central error type makes your library code more consistent and easier to understand.</li><li><strong>Simplicity</strong>: Automatic error conversion reduces the amount of boilerplate code.</li><li><strong>Flexibility</strong>: You can easily add new variants to the central error type if you introduce dependencies that introduce new types of errors.</li></ol><h3>And what if you wanted to add a custom error?</h3><p>It might be necessary to add a specific error for our library, regardless of those that could be triggered by various crates. Let’s suppose the custom error is MyCustomError, representing an application-specific error like a validation error.</p><pre>#[derive(Debug)]<br>pub struct MyCustomError {<br>    details: String,<br>}<br><br>impl MyCustomError {<br>    fn new(msg: &amp;str) -&gt; MyCustomError {<br>        MyCustomError {<br>            details: msg.to_string(),<br>        }<br>    }<br>}<br><br>impl std::fmt::Display for MyCustomError {<br>    fn fmt(&amp;self, f: &amp;mut std::fmt::Formatter) -&gt; std::fmt::Result {<br>        write!(f, &quot;{}&quot;, self.details)<br>    }<br>}<br><br>impl std::error::Error for MyCustomError {}</pre><p>At this point, we could add our error to the enum.</p><pre>use thiserror::Error;<br><br>#[derive(Error, Debug)]<br>pub enum MyLibError {<br>    #[error(&quot;IO error&quot;)]<br>    Io(#[from] std::io::Error),<br><br>    #[error(&quot;JSON serialization error&quot;)]<br>    SerdeJson(#[from] serde_json::Error),<br><br>    #[error(&quot;HTTP request error&quot;)]<br>    Reqwest(#[from] reqwest::Error),<br><br>    #[error(&quot;Custom error: {0}&quot;)]<br>    Custom(#[from] MyCustomError),<br><br>    #[error(&quot;an unknown error occurred&quot;)]<br>    Unknown,<br>}</pre><p>And consequently use it in a function, for example, for validation, just like we did for the other functions previously.</p><pre>fn validate_data(data: &amp;str) -&gt; Result&lt;(), MyLibError&gt; {<br>    if data.is_empty() {<br>        return Err(MyCustomError::new(&quot;Data cannot be empty&quot;).into());<br>    }<br>    Ok(())<br>}</pre><h3>Conclusion</h3><p>As we have seen, despite its simplicity, this crate provides us with extreme flexibility in writing our libraries with just a few lines of code. It also facilitates integrating our custom errors with errors from other crates underlying our project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4b382e389e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/customize-error-handling-with-thiserror-bb4b382e389e">Customize error handling with thiserror</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remote Debugging Rust Applications on Embedded Linux]]></title>
            <link>https://levelup.gitconnected.com/remote-debugging-rust-applications-on-embedded-linux-aaf8b52d7e6a?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/aaf8b52d7e6a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 11:15:05 GMT</pubDate>
            <atom:updated>2024-04-22T11:15:05.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JjNWs1ugYyfCiIYB" /><figcaption>Photo by <a href="https://unsplash.com/@_louisreed?utm_source=medium&amp;utm_medium=referral">Louis Reed</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>One of my first stories talked about cross-compilation in Rust, and how it could be straightforward. If you’re here, probably you’re already able to cross-compile, if not I suggest you to check out that post here:</p><p><a href="https://levelup.gitconnected.com/cross-compile-your-rust-app-for-multiple-architectures-069bf98d0728">Cross-compile your Rust app for multiple architectures</a></p><p>One of the most important aspects in programming is debugging. Often you need not only to compile and execute, but also to debug and watch variables status in order to check byte by byte if everything works fine. This is a really simple procedure today with Rust as with other languages, it tooks few minutes to have your VSCode ready to start a debug session on your computer. Things going to be more complicated if you have an application that needs to run on an embedded Linux device like a Raspberry Pi or similar. In my case for example, I cannot even run the application on my laptop because it needs to access peripherals that only my embedded device has, so it’s important to learn how to setup properly a remote debug session.</p><h4>Step 1 — Install Required Extensions on your PC</h4><p>First, it’s important to specify that in this tutorial I will be using VSCode for debugging, so we need to install (if not already present) the following extensions:</p><ul><li>rust-analyzer</li><li>CodeLLDB</li></ul><p>You probably already have the first extension since it’s essential for coding with this language. The second one is likely installed if you’ve done any local debugging sessions in Rust. Once you’ve confirmed their installation, we’ll move on to the next step.</p><h4>Step 2 — Install the necessary toolchain</h4><p>If you’ve had a look at the link I mentioned earlier, you probably already understand what I’m referring to. In short, we need to download the target platform for the architecture we’ll be using, as well as the cross-compilation and linker tools. To keep this article concise, I’ll refer you to the link above to complete this step.</p><h4>Step 3— Install the Required Sw on Remote Device</h4><p>The third step will involve installing the necessary tool on our embedded Linux device to enable debugging. Let’s access our device and install (if not already present) the following packages:</p><pre>sudo apt-get install gdb gdbserver</pre><p>Of course, the command above is specific to devices that use apt as the package manager. If you&#39;re using dnf or another package manager, please check the package names as they might differ.</p><h4>Step 4 — Create the Shell Script</h4><p>This step involves creating the shell script that will handle the heavy lifting and initiate the debug session. Let’s create a folder named scripts and inside it, create a file named remote_debug.sh with the following content:</p><pre>#!/bin/bash<br><br># Exit immediately if some variables are unset<br>set -o nounset<br># Enable verbose tracing for debug purposes<br>set -o xtrace<br>WS_FOLDER=&quot;$1&quot;<br>APP_NAME=&quot;$2&quot;<br>TARGET_USER=&quot;$3&quot;<br>TARGET_HOST=&quot;$4&quot;<br>TARGET_ARCH=&quot;$5&quot;<br>GDB_PORT=&quot;$6&quot;<br># Set target path<br>TARGET_PATH=&quot;/home/${TARGET_USER}/bin/debug&quot;<br><br># Set binary path to upload<br>SOURCE_PATH=&quot;${WS_FOLDER}/target/${TARGET_ARCH}/debug/${APP_NAME}&quot;<br># Kill previous debug sessions<br>ssh &quot;${TARGET_USER}@${TARGET_HOST}&quot; &quot;killall gdbserver ${APP_NAME}&quot;<br># Secure copy to the target device<br>scp &quot;${SOURCE_PATH}&quot; &quot;${TARGET_USER}@${TARGET_HOST}:${TARGET_PATH}&quot;<br># Start remote debug session<br>ssh -f &quot;${TARGET_USER}@${TARGET_HOST}&quot; &quot;sh -c &#39;cd ${TARGET_PATH}; nohup gdbserver :${GDB_PORT} ./${APP_NAME} &gt; ./console.log 2&gt;&amp;1 &amp;&#39;&quot;</pre><p>The code is already extensively commented. In short, it takes a series of variables that we will provide when we run the script and performs the following operations:</p><ol><li>Set the necessary paths on our PC and on the Linux device</li><li>Attempt to stop any previous sessions of gdb or our software if running</li><li>Copy the executable to the remote device</li><li>Start the debug session</li></ol><h4>Step 5 — Create/Modify the task.json File</h4><p>Let’s check if the task.json file already exists in the .vscode folder, and if not, create the folder and file. Inside this file, we&#39;ll add compilation tasks that can be invoked using the shortcut Ctrl + Shift + B, as well as by the debug invoked from the launch.json file (which we have not created yet). Now, let&#39;s add the following tasks inside task.json:</p><pre>{<br>    &quot;version&quot;: &quot;2.0.0&quot;,<br>    &quot;tasks&quot;: [<br>    {<br>     &quot;label&quot;: &quot;cargo: debug ARMv8&quot;,<br>     &quot;type&quot;: &quot;shell&quot;,<br>     &quot;command&quot;: &quot;cargo&quot;,<br>     &quot;args&quot;: [<br>      &quot;build&quot;,<br>      &quot;--target=aarch64-unknown-linux-gnu&quot;<br>     ],<br>     &quot;problemMatcher&quot;: [<br>      &quot;$rustc&quot;<br>     ],<br>     &quot;group&quot;: {<br>      &quot;kind&quot;: &quot;build&quot;,<br>      &quot;isDefault&quot;: false<br>     }<br>    },<br>    {<br>     &quot;label&quot;: &quot;EmbeddedLinux: remote ARMv8 debug setup&quot;,<br>     &quot;type&quot;: &quot;shell&quot;,<br>     &quot;command&quot;: &quot;${workspaceFolder}/scripts/remote_debug.sh&quot;,<br>     &quot;args&quot;: [<br>      &quot;${workspaceFolder}&quot;, <br>      &quot;embeddedlinux&quot;, <br>      &quot;pi&quot;, <br>      &quot;raspberrypi&quot;, <br>      &quot;aarch64-unknown-linux-gnu&quot;,<br>      &quot;10090&quot; <br>      ],<br>     &quot;group&quot;: {<br>      &quot;kind&quot;: &quot;build&quot;,<br>      &quot;isDefault&quot;: false<br>     },<br>     &quot;dependsOn&quot;: [<br>      &quot;cargo: debug ARMv8&quot;,<br>     ],<br>    },<br>   ]<br>}</pre><p>Alright, there’s quite a bit to unpack here. First, let’s create a task that invokes rustc for cross-compilation targeting aarch64. We won&#39;t actually invoke this task directly; instead, it will be called by the EmbeddedLinux: remote ARMv8 debug setup task, which will be invoked by the launch.json file. This task will be responsible for calling our shell script and passing it the required six arguments:</p><ol><li>Workspace Folder</li><li>Executable name</li><li>Username</li><li>Hostname</li><li>Architecture</li><li>Port</li></ol><p>We are now ready for the final step, which is to create/modify the launch.json file that will handle remote debugging.</p><h4>Step 6 — Create/Modify the launch.json File</h4><p>At this point, everything is set up, and we need to finalize the pipeline that will automate the remote debugging procedure. First, let’s check if our project already has a launch.json file inside the .vscode folder in the project&#39;s root directory. If we&#39;ve already started a debug session locally, VSCode might have prompted us to create one automatically. If not, we&#39;ll need to create the .vscode folder first, then create the launch.json file inside it, and then add the following code into it:</p><pre>{<br>    // Use IntelliSense to learn about possible attributes.<br>    // Hover to view descriptions of existing attributes.<br>    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387<br>    &quot;version&quot;: &quot;0.2.0&quot;,<br>    &quot;configurations&quot;: [<br>        {<br>            &quot;type&quot;: &quot;lldb&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;name&quot;: &quot;Debug executable &#39;polaralp&#39;&quot;,<br>            &quot;cargo&quot;: {<br>                &quot;args&quot;: [<br>                    &quot;build&quot;,<br>                    &quot;--bin=polaralp&quot;,<br>                    &quot;--package=polaralp&quot;<br>                ],<br>                &quot;filter&quot;: {<br>                    &quot;name&quot;: &quot;polaralp&quot;,<br>                    &quot;kind&quot;: &quot;bin&quot;<br>                }<br>            },<br>            &quot;args&quot;: [],<br>            &quot;cwd&quot;: &quot;${workspaceFolder}&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;lldb&quot;,<br>            &quot;request&quot;: &quot;launch&quot;,<br>            &quot;name&quot;: &quot;Debug unit tests in executable &#39;polaralp&#39;&quot;,<br>            &quot;cargo&quot;: {<br>                &quot;args&quot;: [<br>                    &quot;test&quot;,<br>                    &quot;--no-run&quot;,<br>                    &quot;--bin=polaralp&quot;,<br>                    &quot;--package=polaralp&quot;<br>                ],<br>                &quot;filter&quot;: {<br>                    &quot;name&quot;: &quot;polaralp&quot;,<br>                    &quot;kind&quot;: &quot;bin&quot;<br>                }<br>            },<br>            &quot;args&quot;: [],<br>            &quot;cwd&quot;: &quot;${workspaceFolder}&quot;<br>        },<br>        // Below is the part that we&#39;ll use for remote debug<br>        {<br>            &quot;type&quot;: &quot;lldb&quot;,<br>            &quot;request&quot;: &quot;custom&quot;,<br>            &quot;name&quot;: &quot;Embedded Linux Remote Debug&quot;,<br>            &quot;preLaunchTask&quot;: &quot;EmbeddedLinux: remote ARMv8 debug setup&quot;,<br>            &quot;targetCreateCommands&quot;: [&quot;target create ${workspaceFolder}/target/aarch64-unknown-linux-gnu/debug/embeddedlinux&quot;],<br>            &quot;processCreateCommands&quot;: [&quot;gdb-remote raspberrypi:10090&quot;]<br>        }<br>    ]<br>}</pre><p>The first part is simply the default script created when launching an initial debug session. The second part is what we’re interested in, where we create a custom launch configuration. We give it a name, assign a task to run before launch, specify where to find the compiled debug file (assuming “embeddedlinux” is the name of my test project), and finally specify the command that will invoke remote debugging (raspberrypi is the hostname, and 10090 is the port where the debug socket will open).</p><p>By creating a custom launch command, if we go to the Debug section in VSCode and look at the dropdown menu at the top left, we’ll see “Embedded Linux Remote Debug” among the Debug options.</p><h4>Let’s try a debugging session</h4><p>Once you’ve saved your file, you’re ready to test your software. Simply create the most classic of “hello world” or any existing code in your possession in the main.rs file and insert a breakpoint on any line inside the main function. After compiling the code, go to the Debug section of VSCode and select &quot;Embedded Linux Remote Debug&quot; from the dropdown menu at the top left. This will start the remote debug session. You&#39;ll be prompted to enter the password multiple times as the script performs SSH operations.</p><p>After completing these steps, you might find yourself on a page showing the assembly code of your project. Don’t worry; just press F5 or the play button in the debug bar, and your remote session will begin. Like a local debug session, you can set breakpoints and observe the values of each variable, struct, or object in the sidebar while it’s running.</p><h4>Bonus Tip</h4><p>Entering the password two or three times for each session can become tedious, especially when debugging large projects that require frequent restarts. That’s why I suggest using SSH key authentication, which can be quickly enabled with these simple steps:</p><p>Generate a key pair on your computer:</p><pre>ssh-keygen -t rsa</pre><p>Follow the instructions to generate the key pair, you can use the default values provided. Once completed, copy the public key to the remote device:</p><pre>ssh-copy-id username@hostname</pre><p>Where username and hostname are those of your device, which you already used for the previous remote debugging setup. Once the process is complete, try connecting via SSH to your device, and you will see that access is automatic, without requiring additional passwords.</p><h4>In Conclusion</h4><p>Debugging remotely directly on our embedded Linux device allows us to elevate our capabilities and work with the same level of control as we would when debugging firmware with a dedicated debugger or software running locally on our PC. I hope this article has been of interest to you, and I encourage you to give it a clap or reach out to me with any questions you may have.</p><p>Thank you for your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aaf8b52d7e6a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/remote-debugging-rust-applications-on-embedded-linux-aaf8b52d7e6a">Remote Debugging Rust Applications on Embedded Linux</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting a Rust URL Shortener: Part 3— Building Frontend]]></title>
            <link>https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-3-building-frontend-33409282083f?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/33409282083f</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[htmx]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 23:34:41 GMT</pubDate>
            <atom:updated>2024-02-20T23:34:41.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LI36swDVkmtYLHIsbbMUeA.jpeg" /></figure><p>Hello and welcome to the third part of our tutorial, where we will create a simple Rust URL shortener. In previous parts, we set up our project, created a PostgreSQL database with Docker, managed migration and communication with SQLx, and created a basic backend with Axum. At the end of Part 2, we were able to test APIs from a Postman-like client. In case you missed previous parts here’s the link to the first one.</p><p><a href="https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-1-setting-up-your-project-9babe97b8962">Crafting a Rust URL Shortener: Part 1 — Setting Up Your Project</a></p><p>Today, I’d like to close the loop and build a minimal frontend to shorten URLs directly from a web page, without relying on other tools. To do that, we’ll follow these steps:</p><ol><li>Create a route to display our web page.</li><li>Design our web page with some styling using Bootstrap.</li><li>Integrate HTMX into our form to enable URL shortening functionality.</li></ol><h3>Adding a route</h3><p>To proceed, we must incorporate a third route into our project. In previous steps, we crafted a POST request to shorten URLs and a GET request to retrieve the original URL, redirecting users accordingly. Now, we’ll introduce another GET request that serves a web page when accessed from a browser. This involves augmenting our handler.rs file with additional code.</p><pre>pub async fn app() -&gt; impl IntoResponse {<br>    let template = AppTemplate {};<br>    HtmlTemplate(template)<br>}<br><br>#[derive(Template)]<br>#[template(path = &quot;app.html&quot;)]<br>struct AppTemplate;<br><br>/// A wrapper type that we&#39;ll use to encapsulate HTML parsed by askama into valid HTML for axum to serve.<br>struct HtmlTemplate&lt;T&gt;(T);<br><br>/// Allows us to convert Askama HTML templates into valid HTML for axum to serve in the response.<br>impl&lt;T&gt; IntoResponse for HtmlTemplate&lt;T&gt;<br>where<br>    T: Template,<br>{<br>    fn into_response(self) -&gt; Response {<br>        // Attempt to render the template with askama<br>        match self.0.render() {<br>            // If we&#39;re able to successfully parse and aggregate the template, serve it<br>            Ok(html) =&gt; Html(html).into_response(),<br>            // If we&#39;re not, return an error or some bit of fallback HTML<br>            Err(err) =&gt; (<br>                StatusCode::INTERNAL_SERVER_ERROR,<br>                format!(&quot;Failed to render template. Error: {}&quot;, err),<br>            )<br>                .into_response(),<br>        }<br>    }<br>}</pre><p>In this step, we’ll create a handler that we’ll later route in our http.rs file. This handler will serve the app.html page, which we&#39;ll write shortly. Additionally, we&#39;ll implement the IntoResponse trait to properly manage Askama templates and render the page.</p><p>Don’t worry if you encounter errors; they may occur because we haven’t yet created the templates folder with the app.html file inside it. We&#39;ll rectify this shortly. For now, let&#39;s proceed by modifying our http.rs file to incorporate the route responsible for handling our web page.</p><pre>fn api_router(app_state: Arc&lt;AppState&gt;) -&gt; Router {<br>    Router::new()<br>        .route(&quot;/&quot;, get(handler::app).post(handler::post_url))<br>        .route(&quot;/:url&quot;, get(handler::get_url))<br>        .with_state(app_state)<br>}</pre><p>Now that the route is established, we can proceed with writing our HTML code. <a href="https://medium.com/gitconnected/super-fast-http-server-with-rust-htmx-part-1-bfcddbd6e8bc">In my previous tutorial</a>, I developed the example with an embedded environment in mind, necessitating the availability of all resources offline within my project. However, this time around, I don’t have the same constraints, affording me the opportunity to streamline by linking Bootstrap and htmx directly from a CDN rather than downloading and utilizing them locally.</p><p>However, I still prefer to organize my frontend into smaller components for better readability. Therefore, I’ll employ Askama again to achieve this, even though I may not utilize all of its features. Below is the base.html:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>    &lt;title&gt;Rust URL Shortener&lt;/title&gt;<br>    &lt;link href=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot; integrity=&quot;sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css&quot;&gt;<br>    <br>    &lt;script src=&quot;https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js&quot; integrity=&quot;sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>    &lt;script src=&quot;https://unpkg.com/htmx.org@1.9.10&quot;&gt;&lt;/script&gt;<br>    &lt;style&gt;<br>        body {<br>          background-color: #121212;<br>          color: #fff;<br>        }<br>        .form-control {<br>          background-color: #333;<br>          border-color: #333;<br>          color: #fff;<br>        }<br>        .btn-primary {<br>          background-color: #007bff;<br>          border-color: #007bff;<br>        }<br>        .btn-primary:hover {<br>          background-color: #0056b3;<br>          border-color: #0056b3;<br>        }<br>      &lt;/style&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-md-6 offset-md-3 mt-5&quot;&gt;<br>                &lt;h1 class=&quot;text-center mb-4&quot;&gt;Rust URL Shortener&lt;/h1&gt;<br>                {% block content %}{% endblock %}<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;</pre><p>As evident, this time it’s much simpler. We only require links to Bootstrap and htmx, along with a bit of CSS, and we’re good to go. Now, let’s proceed to write the app.html section where we&#39;ll incorporate the form responsible for managing the URL shortener&#39;s requests.</p><pre>{% extends &quot;base.html&quot; %}<br><br><br>{% block content %}<br>&lt;form <br>    hx-post=&quot;/&quot;<br>    hx-target=&quot;#shortened-url&quot;<br>    hx-swap=&quot;innerHtml&quot;<br>    &gt;<br>    &lt;div class=&quot;mb-3&quot;&gt;<br>        &lt;label for=&quot;url&quot; class=&quot;form-label&quot;&gt;Paste the URL to be shortened&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;url&quot; name=&quot;url&quot; placeholder=&quot;Enter the link here&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Shorten URL&lt;/button&gt;<br>&lt;/form&gt;<br><br>{% include &quot;url.html&quot; %}<br><br>{% endblock %}</pre><p>In this section, we’re utilizing htmx to facilitate the POST request responsible for shortening the URL. The target attribute points to an ID that is not present in this file. However, there’s no need to worry as I’ve opted to split it into another file named url.html:</p><pre>&lt;div class=&quot;mt-5&quot;&gt;<br>    &lt;p&gt;Shortened URL&lt;/p&gt;<br>    &lt;div class=&quot;form-control&quot; id=&quot;shortened-url&quot;&gt;...&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Essentially, upon invocation, the POST request will return the shortened URL, and htmx will then replace the content of the div with the shortened URL. However, if you attempt to run this code now and try to shorten a URL, it won&#39;t work. This is because in my previous tutorial, I selected a return type for my route that functions well for Postman or other clients but not for our frontend. Therefore, we need to make some minor adjustments to our handler.rs:</p><pre>pub async fn post_url(https://medium.com/%3Cbr%3E%20%20%20%20State(state): State&lt;Arc&lt;AppState&gt;&gt;,<br>    Form(form_data): Form&lt;FormData&gt;,<br>) -&gt; Html&lt;String&gt; {<br>    // Check if the provided URL is valid<br>    if Url::parse(&amp;form_data.url).is_ok() {<br>        // Generate url random part<br>        match shorten_url(https://medium.com/&amp;state.db,%20form_data.url).await {<br>            Ok(result) =&gt; Html(format!(&quot;{}{}&quot;, BASE_URL, result)),<br>            Err(err) =&gt; Html(format!(&quot;Something went wrong: {}&quot;, err)),<br>        }<br>    } else {<br>        Html(&quot;This is not a valid URL&quot;.to_string())<br>    }<br>}</pre><p>The primary modification lies in changing the function return type from Response&lt;String&gt; to Html&lt;String&gt;. Consequently, we&#39;ll need to make some minor adjustments in the match arms to ensure the correct data is returned. Once these changes are implemented, we&#39;re ready to compile and test our app. We can visit localhost:8086 from our browser, where we&#39;ll encounter our simple form. Upon attempting to shorten a URL, we should see the shortened URL displayed below the form, akin to the image depicted below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ViYTM3ALvJxgJ0OWjM7o7A.png" /></figure><p>Great! It seems like everything is working smoothly. If you paste the shortened URL into the browser’s search bar, you’ll notice that the GET request functions correctly, redirecting you to the original URL. Additionally, if you try inputting an incorrect URL, you’ll receive a proper notification. Feel free to give it a try!</p><h3>In Conclusion</h3><p>This marks the conclusion of our tutorial. By now, you should have a simple yet functional URL shortener. There are numerous ways to enhance it further, such as incorporating features like visit count tracking for analytics, storing additional information in the database, or refining the frontend design for a more polished appearance. Feel free to explore and expand upon the project using my <a href="https://github.com/deid84/shorturl-rs">GitHub repository</a> as a starting point. I hope you found this tutorial enjoyable and insightful. Don’t forget to show your support by clapping or following me to stay updated on future stories and tutorials. Thank you for joining me on this journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33409282083f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-3-building-frontend-33409282083f">Crafting a Rust URL Shortener: Part 3— Building Frontend</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting a Rust URL Shortener: Part 2— Creating APIs]]></title>
            <link>https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-2-creating-apis-1753b4789816?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/1753b4789816</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 13:22:03 GMT</pubDate>
            <atom:updated>2024-02-19T13:22:03.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMxz8Xc57VZ67lUyxDwIrQ.jpeg" /></figure><p>Welcome to the second part of our tutorial on creating a simple and lightweight URL shortener with Rust. In the first part, we began by setting up our project and preparing the necessary code and tools to run a Docker container with a Postgres database. We installed SQLx to create and apply our first migration, along with basic Rust code to connect to the database. In case you missed the first part, here’s the link.</p><p><a href="https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-1-setting-up-your-project-9babe97b8962">Crafting a Rust URL Shortener: Part 1 — Setting Up Your Project</a></p><h3>What’s on Today’s Agenda?</h3><p>Today, we’ll implement the backend APIs necessary to run the app. Since this is a simple tutorial focused on creating a basic implementation, we primarily require two routes, one for <strong>POST</strong> and another for <strong>GET</strong> methods, respectively. To implement them, we’re going to use <strong>Axum</strong> for creating <strong>HTTP</strong> routes, along with a couple of crates that we likely installed in the first part of this tutorial: rand and url.</p><h4>The POST Method</h4><p>The first route will be a POST route that manages the creation of the short URL given the original one. The logic behind this request will be something like this:</p><ol><li>Create the Axum route with an extractor to obtain the user URL from the HTTP body.</li><li>Use the url crate to check if the user&#39;s URL is valid.</li><li>Use rand to generate a 4-character-long base62 string.</li><li>Check in the database if this random string does not already exist. If it does, retry until a non-existing string is found.</li><li>Save a record in the database with the random string as the primary key and the original URL as the other value.</li><li>Return to the user the shortened URL, which consists of ‘our_website_url’ + ‘/random_string’.</li></ol><p>Since our website URL is a constant part, there’s no need to store it in the database for each new record. Instead, we’ll save only the random part of the shortened URL. When returning the shortened URL to the user, we’ll merge this random part with our website URL. As mentioned in the previous article, we’re using only a 4-character-long string because more than 12 million combinations are far more than the attempts one would typically make before becoming bored. However, if you plan to create a production version of this tutorial to manage a larger number of URLs, you may want to consider using more characters for the random part.</p><h4>The GET Method</h4><p>The GET method is the simplest route. We only need to extract the URL from the request and query our database for the 4-character string at the end of the URL. If the primary key is found, it redirects the user to the original long URL that was saved with that primary key.</p><h3>Hands on</h3><p>First of all, let’s create an http.rs file in the src folder and a http folder that contains these three files as follows:</p><pre>http<br>├── handler.rs<br>├── model.rs<br>└── service.rs</pre><p>I don’t want to have overly long files, so I’ve decided to split my backend into the following components:</p><ul><li>model: This will host a struct representing my database table.</li><li>handler: Alternatively known as the controller, this is where I&#39;ll write functions to handle requests from the frontend.</li><li>service: This is where I&#39;ll use the data extracted from the handler to perform logic and interact with the database.</li></ul><h4>Model</h4><p>In our model.rs let’s write the following code:</p><pre>use serde::{Deserialize, Serialize};<br><br>/// This struct represents the URL db table: `id` and `long_url`.<br>/// <br>#[derive(Serialize, Deserialize)]<br>pub struct Url {<br>    /// The random shorturl string<br>    pub id: String,<br>    /// The long URL corresponding to the short URL.<br>    pub long_url: String,<br>}</pre><p>Here, we declare a struct that represents our database table. SQLx will utilize this struct to map values to and from PostgreSQL. In a production-ready project, it’s standard practice to encapsulate access to struct fields using getter and setter methods to provide better control and encapsulation of the internal state. This approach allows for validation, error handling, and other checks before accessing or modifying the fields. However, for the sake of simplicity and straightforwardness in our project, we have opted to use public fields directly for the Url struct.</p><h4>Service</h4><p>In our service.rs we’ll write the following code:</p><pre>use anyhow::Result;<br>use rand::{distributions::Alphanumeric, Rng};<br>use sqlx::{Error, Pool, Postgres};<br><br>use super::model::Url;<br><br>const MAX_RETRIES: usize = 5;<br>const SHORTURL_LEN: usize = 4;<br><br>pub async fn resolve_short_url(/service/db: &amp;Pool&lt;Postgres&gt;, url: String) -&gt; Result&lt;String, Error&gt; {<br>    // Check if random string already exists in db<br>    match sqlx::query_as!(<br>        Url,<br>        r#&quot;SELECT * FROM url <br>                WHERE id = $1&quot;#,<br>        url<br>    )<br>    .fetch_one(db)<br>    .await<br>    {<br>        Ok(data) =&gt; {<br>            // The URL has been found in the database, returning the corresponding long URL<br>            Ok(data.long_url)<br>        }<br>        Err(err) =&gt; {<br>            // An error occurred during the database operation, returning the error<br>            Err(err.into())<br>        }<br>    }<br>}<br><br>pub async fn shorten_url(/service/db: &amp;Pool&lt;Postgres&gt;, url: String) -&gt; Result&lt;String, Error&gt; {<br>    // Loop for a maximum number of retries<br>    for _ in 0..MAX_RETRIES {<br>        let rng = rand::thread_rng();<br><br>        // Generate a random string for the short URL<br>        let random_string: String = rng<br>            .sample_iter(&amp;Alphanumeric)<br>            .take(SHORTURL_LEN)<br>            .map(char::from)<br>            .collect();<br><br>        // Try to insert data in the db<br>        match sqlx::query_as!(<br>            Url,<br>            r#&quot;INSERT INTO url (id, long_url) <br>            VALUES ($1, $2)<br>            RETURNING id, long_url;&quot;#,<br>            random_string,<br>            url<br>        )<br>        .fetch_one(db)<br>        .await<br>        {<br>            Ok(_) =&gt; {<br>                // Successful insertion, return the generated random string<br>                return Ok(random_string);<br>            }<br>            Err(err) =&gt; {<br>                // Check if the error is due to a unique constraint violation (value already exists)<br>                if let sqlx::Error::Database(db_err) = &amp;err {<br>                    if db_err.is_foreign_key_violation() {<br>                        // Retry inserting with a new random string<br>                        continue;<br>                    }<br>                }<br>                // If it&#39;s not a unique constraint violation or if the maximum retries are reached, return the error<br>                return Err(err);<br>            }<br>        }<br>    }<br>    // If maximum retries are reached without successful insertion, return an error<br>    Err(Error::Io(std::io::Error::new(<br>        std::io::ErrorKind::Other,<br>        &quot;Maximum retries reached without successful insertion&quot;,<br>    )))<br>}</pre><p>The code comprises two main functions.</p><p>resolve_short_url verifies if a short URL exists in our database. If it finds a corresponding entry, it returns the associated full URL, which will be utilized in the subsequent handler function defined later in the code.</p><p>shorten_url receives the full URL that needs to be shortened. Upon receiving this input, it utilizes the rand crate to generate a random 4-character base62 string (you can adjust the length as needed).</p><p>After generating the random string, the function attempts to save it in the database. However, due to the randomness, there’s a possibility that the generated string already exists. To circumvent this unique constraint, the function retries a specified number of times. If the SQLx error returned indicates a <strong>UNIQUE_CONSTRAINT</strong> violation, the function generates another random string and tries again. This process continues until a unique string is found and successfully stored in the database, upon which the short URL is returned.</p><p>If the function encounters other types of errors during this process or exhausts the maximum number of retries, it exits with an error.</p><h4>Handler</h4><p>In our handler, we integrate the service functions previously defined into the routing logic to handle both GET and POST requests:</p><pre>use std::sync::Arc;<br><br>use axum::{<br>    extract::{Path, State},<br>    http::{Response, StatusCode},<br>    Form,<br>};<br>use serde::Deserialize;<br>use url::Url;<br><br>use super::{<br>    service::{resolve_short_url, shorten_url},<br>    AppState,<br>};<br><br>// Change it with the URL where you&#39;ll host your project<br>const BASE_URL: &amp;str = &quot;localhost:8086/&quot;;<br><br>// Struct to manage frontend form data<br>#[derive(Deserialize)]<br>pub struct FormData {<br>    url: String,<br>}<br><br>pub async fn get_url(https://medium.com/%3Cbr%3E%20%20%20%20State(state): State&lt;Arc&lt;AppState&gt;&gt;,<br>    Path(url): Path&lt;String&gt;,<br>) -&gt; Response&lt;String&gt; {<br>    // Attempt to resolve the short URL to its corresponding long URL<br>    match resolve_short_url(https://medium.com/&amp;state.db,%20url).await {<br>        Ok(result) =&gt; Response::builder()<br>            // If resolution is successful, construct a response indicating a permanent redirect (status code 301)<br>            // Set the &#39;Location&#39; header to the resolved long URL and provide a body with a redirection message<br>            .status(StatusCode::MOVED_PERMANENTLY)<br>            .header(&quot;Location&quot;, result)<br>            .body(format!(&quot;Redirecting...&quot;))<br>            .unwrap(),<br>        Err(err) =&gt; Response::builder()<br>            // If an error occurs during resolution, construct a response with a &#39;404 Not Found&#39; status code<br>            // Include the error message in the response body to indicate the failure<br>            .status(StatusCode::NOT_FOUND)<br>            .body(format!(&quot;Sorry your short URL does not exist!&quot;))<br>            .unwrap(),<br>    }<br>}<br><br>pub async fn post_url(https://medium.com/%3Cbr%3E%20%20%20%20State(state): State&lt;Arc&lt;AppState&gt;&gt;,<br>    Form(form_data): Form&lt;FormData&gt;,<br>) -&gt; Response&lt;String&gt; {<br>    // Check if the provided URL is valid<br>    if let Ok(_) = Url::parse(&amp;form_data.url) {<br>        // Generate url random part<br>        match shorten_url(https://medium.com/&amp;state.db,%20form_data.url).await {<br>            Ok(result) =&gt; Response::builder()<br>                // If shortening is successful, construct a response with status code &#39;200 OK&#39;<br>                // Include the shortened URL in the response body prefixed with the base URL<br>                .status(StatusCode::OK)<br>                .body(format!(&quot;{}{}&quot;, BASE_URL, result))<br>                .unwrap(),<br>            Err(err) =&gt; Response::builder()<br>                // If an error occurs during shortening, construct a response with status code &#39;500 Internal Server Error&#39;<br>                // Include the error message in the response body to indicate the failure<br>                .status(StatusCode::INTERNAL_SERVER_ERROR)<br>                .body(err.to_string())<br>                .unwrap(),<br>        }<br>    } else {<br>        Response::builder()<br>            // If the provided URL is not valid, construct a response with status code &#39;500 Internal Server Error&#39;<br>            // Include a message in the response body indicating that the URL is not valid<br>            .status(StatusCode::INTERNAL_SERVER_ERROR)<br>            .body(format!(&quot;Not a URL!&quot;))<br>            .unwrap()<br>    }<br>}</pre><p>Again I tried to write some comments in the code but here’s what’s going on:</p><p>The get_url function retrieves the short URL from the Path using the Axum Path extractor. Upon extraction, it invokes the resolve_short_url service function to verify if the short URL exists in the database.</p><p>If a corresponding entry is found, indicating the existence of the short URL, the function receives the original URL. Utilizing the Response Builder, it constructs a 301 redirection response, directing the client to the desired website.</p><p>In cases where the short URL is not found in the database, the function responds with a 404 Not Found status code, indicating that the requested resource could not be located.</p><p>The post_url function retrieves the URL to shorten from the Axum Form extractor, which is chosen for its compatibility with a future frontend that handles requests through URL-encoded forms. Upon extraction, the function utilizes the url crate to validate the URL provided.</p><p>After validation, the function invokes the shorten_url service function to obtain the corresponding short URL. Since the short URL consists only of a 4-character unique identifier, it needs to be combined with the base URL of our website to create a functional route for the get_url function. For simplicity, a constant storing the localhost address is concatenated with the short URL to form the complete URL returned to the user.</p><p>In cases where the provided URL is invalid or if an error occurs during database interaction, the function responds with an internal server error code (500) to inform the user about the issue.</p><h4>Axum HTTP Backend</h4><p>Let’s bring together all the components we’ve developed into the Axum backend. Below is the code snippet encapsulating our implementation, located in the http.rs file:</p><pre>use std::sync::Arc;<br><br>use anyhow::Result;<br>use axum::{http::StatusCode, routing::get, Router};<br>use sqlx::{PgPool, Pool, Postgres};<br><br>mod handler;<br>mod model;<br>mod service;<br><br>/// This struct represents the application state, holding a database connection pool<br>struct AppState {<br>    db: Pool&lt;Postgres&gt;,<br>}<br><br>/// This function serves as the entry point for running the Axum web server.<br>/// It takes a PostgreSQL connection pool (`PgPool`) as input, sets up the application state, <br>/// creates the API routes using the provided application state, binds the server to a specific port,<br>/// and starts serving incoming connections.<br>pub async fn serve(db: PgPool) -&gt; Result&lt;()&gt; {<br>    // Set up the application state with the provided database connection pool<br>    let app_state = AppState { db };<br>    // Create the API routes using the application state<br>    let app = api_router(Arc::new(app_state));<br>    let port = 8086;<br>     // Bind the server to the specified address and port<br>    let address = tokio::net::TcpListener::bind(format!(&quot;0.0.0.0:{}&quot;, port)).await?;<br>    // Start serving incoming connections<br>    axum::serve(address, app.into_make_service()).await?;<br>    Ok(())<br>}<br><br>/// This function defines the API routes for the application.<br>/// It takes the application state as input and sets up the routes for handling different HTTP methods and endpoints.<br>fn api_router(app_state: Arc&lt;AppState&gt;) -&gt; Router {<br>    Router::new()<br>        .route(&quot;/&quot;, get(home).post(handler::post_url))<br>        .route(&quot;/:url&quot;, get(handler::get_url))<br>        .with_state(app_state)<br>}<br><br>/// To be completed in next part<br>async fn home() -&gt; Result&lt;String, StatusCode&gt; {<br>    Err(StatusCode::NOT_FOUND)<br>}</pre><p>In this section, we’ll establish an AppState to manage a PostgreSQL pool, allowing it to be shared across our routes. Subsequently, we&#39;ll construct a straightforward Axum router to handle both GET and POST requests, where we&#39;ll integrate our handler functions.</p><p>While many tutorials, including previous ones like the example created for htmx, typically consolidate all code within a single file, today we’ll adopt a best practice by distributing our code across smaller, modularized files. This approach enhances readability and maintainability by organizing our code into more manageable components.</p><p>Now, all that remains is to update our main.rs file to initiate our HTTP server:</p><pre>use anyhow::Result;<br>use dotenvy::dotenv;<br>use dotenvy_macro::dotenv;<br><br>mod db;<br>mod http;<br><br>#[tokio::main]<br>async fn main() -&gt; Result&lt;()&gt; {<br>    // Load environment variables from the `.env` file<br>    dotenv().ok();<br>    // Retrieve the value of the `DATABASE_URL` env variable<br>    let db_url = dotenv!(&quot;DATABASE_URL&quot;).to_owned();<br>    // Connect to Postgres database<br>    let db = db::connect(db_url).await?;<br>    // Start the http server<br>    http::serve(db).await?;<br>    Ok(())<br>}</pre><h3>Trying It Out</h3><p>Alright, it’s time to put our backend to the test. If you haven’t already, ensure your container is up and running. Don’t forget to execute sqlx migrate run to populate your database, as we&#39;re currently not utilizing any volumes for persistent data storage.</p><p>Once that’s done, fire up our Rust project with cargo run. Upon successful connection, we&#39;re ready to begin testing our backend functionality.</p><p>To start off, let’s try shortening a URL. Since this involves submitting a form body containing our URL, we’ll need to simulate it. If you’re using Postman or Insomnia, you’re all set. Otherwise, you can opt for Thunder Client, a convenient VS Code plugin for managing HTTP requests directly from the editor.</p><p>Create a POST request to the URL localhost:8086, and select Form-encode in the Body section. Add a field with the key url and set its value to the URL you wish to shorten. Now, send the request, and you&#39;ll receive a response containing the shortened URL. In my case, as depicted in the image below, it appears as ~localhost:8086/Ipl6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oV1mAKa1lwcYbdzc8s0VpA.png" /><figcaption>POST request made with Thunder Client</figcaption></figure><p>Now, let’s put our shortened URL to the test. Since it’s a straightforward GET request with the short URL as a parameter, we can easily try it out directly from our browser.</p><p>Open your preferred browser and enter the shortened URL. If it exists in our system, you’ll be seamlessly redirected to the corresponding website. However, if the URL doesn’t exist, you’ll encounter the error message previously defined in our handler.</p><h3>Conclusion</h3><p>We’ve reached the conclusion of this second part of our URL shortener tutorial. Today, we’ve successfully developed the backend logic, enabling us to generate short URLs and seamlessly redirect users to the original websites.</p><p>In the upcoming segment, we’ll dive into implementing a simple frontend, allowing us to interact with our URL shortener without the need for external tools like Thunder Client or similar.</p><p>If you’d like to review the full code, you can access it on my <a href="https://github.com/deid84/shorturl-rs">GitHub repository.</a> Additionally, I’ve included a modified YAML file for Docker Compose, which creates a volume to alleviate the need for running migrations every time you start your container.</p><p>Your feedback is invaluable to me! Whether you’d like to reach out here or open an issue on <a href="https://github.com/deid84/shorturl-rs">GitHub</a>, I’m eager to hear your thoughts.</p><p>Don’t forget to show your support by clapping or following me to stay updated on future content. Thank you for joining me on this journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1753b4789816" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-2-creating-apis-1753b4789816">Crafting a Rust URL Shortener: Part 2— Creating APIs</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting a Rust URL Shortener: Part 1 — Setting Up Your Project]]></title>
            <link>https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-1-setting-up-your-project-9babe97b8962?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/9babe97b8962</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 04:20:12 GMT</pubDate>
            <atom:updated>2024-02-12T21:49:08.280Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crafting a Rust URL Shortener: Part 1 — Setting Up Your Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYrTUyOU-1IY1M8FP48kdQ.jpeg" /></figure><p>Hello everyone, today I’m excited to kick off a new series of articles where we’ll dive into developing a <em>URL shortener in Rust</em>. I’m sticking with these <em>‘hands-on’ </em>stories because they’re the type of content I enjoy writing the most, and the positive reception of my latest tutorial (2 medium boosts in 2 months) has inspired me to continue in this direction. If you missed my previous tutorial, you can find the link here.</p><p><a href="https://levelup.gitconnected.com/super-fast-http-server-with-rust-htmx-part-1-bfcddbd6e8bc">Super fast http server with Rust + htmx (part 1)</a></p><h3>The Project</h3><p>As you might have guessed from the title, today we embark on the journey of creating a URL shortener in Rust. Our goal is to cover everything from setting up the database and backend to crafting a simple user interface, resulting in a full-stack solution. We’ll begin by establishing a database to store our URLs, followed by implementing the backend to handle <strong>GET</strong> and <strong>POST</strong> requests while ensuring the validity of the URLs and potentially tracking some analytics. Finally, we’ll focus on designing a sleek and user-friendly interface to facilitate interaction with our project.</p><p>Given the scope of these tasks, I’ve chosen to divide this tutorial into multiple articles. While I haven’t determined the exact number yet, I anticipate at least three articles. This approach not only allows us to delve into each section thoroughly but also prevents overwhelming readers with lengthy, single-page tutorials. Instead, we’ll wrap up each section neatly before moving on to the next.</p><h3>The Stack</h3><ul><li><strong>Rust:</strong> Yes, I understand it might sound repetitive, but it’s the language I’m passionate about, so I’ll continue to embrace it!</li><li><strong>Axum:</strong> If you’ve read my previous article, you might already be aware that it’s my preferred tool for backend development.</li><li><strong>PostgreSQL: </strong>This will serve as the database where we store our URLs, along with potential analytics-related data.</li><li><strong>Docker: </strong>Even though it might not be the optimal choice for production, I’ve opted to use it because, for teaching purposes, it significantly accelerates the setup phase.</li><li><strong>Askama:</strong> Though I’ve heard there are faster alternatives, given my time constraints, I’ll stick with it for now for templating.</li><li><strong>htmx:</strong> I’ve had a positive experience with it in my previous tutorial, so I’d like to delve deeper into it this time to give my frontend reactivity.</li><li><strong>Bootstrap:</strong> To avoid too much similarity with my previous tutorial, I’ve decided to switch from Tailwind to Bootstrap for styling the frontend.</li></ul><h3>Setting Up The Project</h3><p>First, let’s create our project, which we’ll call shorturl-rs. To set it up, execute the command cargo new shorturl-rs in your terminal. Then, open the newly created project with your preferred text editor. Once inside, let’s start adding some crates to it:</p><pre>[package]<br>name = &quot;shorturl-rs&quot;<br>authors = [&quot;Davide Ferrero&quot;]<br>description = &quot;Rust Simple &amp; Lightweight URL Shortener&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>anyhow = &quot;1.0.79&quot;<br>askama = &quot;0.12.1&quot;<br>axum = &quot;0.7.4&quot;<br>rand = &quot;0.8.5&quot;<br>sqlx = { version = &quot;0.7.3&quot;, features = [&quot;runtime-tokio&quot;, &quot;postgres&quot;] }<br>tokio = { version = &quot;1.36.0&quot;, features = [&quot;full&quot;] }<br>tower = &quot;0.4.13&quot;<br>url = &quot;2.5.0&quot;</pre><p>Although we may incorporate more features later, our current setup provides a solid foundation. Let’s kick things off by running cargo build to fetch and compile all the required crates.</p><p>As you’ve noticed, I’ve opted to use <strong>SQLx</strong> for managing database queries with <strong>PostgreSQL</strong>. While <strong>ORM</strong> libraries like <strong>Diesel</strong> or <strong>SeaORM</strong> are popular choices, I prefer sticking to<em> traditional SQL queries</em>. SQLx offers a compromise by providing assistance through compile-time checked queries while still allowing me to use SQL directly. Additionally, its <strong>sqlx-cli</strong> tool simplifies database interaction by facilitating migration creation, management, and rollback.</p><p>It’s worth mentioning that sqlx-cli isn’t installed automatically with SQLx. Therefore, to use it, we’ll need to install it separately. Since I frequently use sqlx-cli across multiple projects, I’ve chosen to install it globally. To do so, simply run cargo install sqlx-cli. After the installation is complete, we’re ready to proceed to the next step.</p><h3>Setting Up Postgres</h3><p>Alright, it’s time to integrate a database into our project. While many tutorials often default to <strong>SQLite</strong> for its simplicity, our project, envisioned as a high-traffic URL shortener, demands a more robust solution capable of handling numerous requests and concurrent write accesses. Therefore, I’ve opted for <strong>PostgreSQL</strong>.</p><p>To streamline the setup process, especially given the complexity of configuring PostgreSQL compared to SQLite, I’ve chosen to utilize <strong>Docker</strong>. While this setup may not align with production practices, it serves as a convenient solution for testing purposes within this tutorial.</p><p>Assuming you already have Docker installed on your machine (if not, the official guide is user-friendly), the next step involves creating a docker-compose.yml file. This file will contain instructions for spinning up a PostgreSQL container. Let&#39;s dive into that now.</p><pre>version: &#39;3.8&#39;<br><br>services:<br>  db:<br>    image: postgres<br>    restart: always<br>    environment:<br>      POSTGRES_USER: davide<br>      POSTGRES_PASSWORD: deid84<br>      POSTGRES_DB: shorturl-rs<br>    ports:<br>      - 5432:5432</pre><p>This script instructs Docker to pull the latest PostgreSQL image and create a database with the provided details. It’s a straightforward process. After creating this file, we can execute it by running the command docker compose up -d. This command runs our PostgreSQL container in detached mode, allowing us to continue using our terminal for other tasks.</p><p>Now we can utilize sqlx-cli to connect to the database and create our initial migration. You have the option to pass database information through a variable from the terminal or by creating a .env file in your project. For simplicity, I&#39;ve chosen the latter option. Let&#39;s create a .env file and write the database connection string inside it.</p><pre>DATABASE_URL=postgres://davide:deid84@localhost:5432/shorturl-rs</pre><p>After creating the .env file, let&#39;s generate our first migration by running sqlx migrate add url. This command generates a SQL file called ‘url’ inside a migrations folder. Each filename includes a timestamp to ensure migrations are executed in chronological order.</p><pre>migrations<br>└── 20240210221957_url.sql</pre><p>Now, let&#39;s add the definition for our first database table inside the newly created file.</p><pre>-- Add migration script here<br>CREATE TABLE &quot;url&quot; (<br>    id VARCHAR(4) PRIMARY KEY,<br>    long_url VARCHAR NOT NULL<br>);</pre><p>We’ve begun creating a url table with two columns: one for our short URL, which will also serve as the primary key, and another to store the full URL. I’ve chosen a 4-character string for the short URL version. With a base62 alphanumeric string, we’ll have over 14 million combinations. I believe this will be sufficient for our testing purposes. Don&#39;t worry if you&#39;re uncertain about the details of database storage; we can refine and adjust as needed. If additional tables or columns are required, we can always implement them later through additional migrations.</p><p>To execute the migration and apply changes to our database, we need to run sqlx migrate run. This command will apply all SQL files in the migrations folder in chronological order. Since we only have one migration command for now, you&#39;ll probably see something like this:</p><pre>❯ sqlx migrate run<br>Applied 20240210221957/migrate url (3.182363ms)</pre><p>Perfect, so now we have a postgres container running with a db inside that has our migration correctly applied. The environment looks good to go further.</p><h3>Connecting to Our Database</h3><p>Now that migration is running properly, we can begin writing into our Rust project. As promised, I noticed that in the Cargo.toml file, we need to add two additional crates. Let&#39;s type cargo add dotenvy and cargo add dotenvy-macro to install them. Once installed, we can start adding some code to our main.rs file.</p><pre>use anyhow::Result;<br>use dotenvy::dotenv;<br>use dotenvy_macro::dotenv;<br><br>mod db;<br><br>#[tokio::main]<br>async fn main() -&gt; Result&lt;()&gt; {<br>    // Load environment variables from the `.env` file<br>    dotenv().ok();<br>    // Retrieve the value of the `DATABASE_URL` env variable<br>    let db_url = dotenv!(&quot;DATABASE_URL&quot;).to_owned();<br>    // Connect to Postgres database<br>    let _db = db::connect(db_url).await?;<br>    Ok(())<br>}</pre><p>You may encounter some errors, but don’t worry, it’s normal because we’re calling a module and its respective function that haven’t been created yet. Let’s add a db.rs file with the following code inside:</p><pre>use anyhow::{Context, Result};<br>use sqlx::postgres::PgPoolOptions;<br>use sqlx::{Pool, Postgres};<br><br>/// Create a new `PgPoolOptions` instance and set the<br>/// maximum number of connections in the connection pool to 50.<br>pub async fn connect(db_url: String) -&gt; Result&lt;Pool&lt;Postgres&gt;&gt; {<br>    let db = PgPoolOptions::new()<br>        .max_connections(50)<br>        .connect(&amp;db_url)<br>        .await<br>        .context(&quot;Error: unable to connect to database!&quot;)?;<br><br>    println!(&quot;Successfully connected to database.&quot;);<br><br>    Ok(db)<br>}</pre><p>We’re ready to test our first code. Let’s type cargo run. If you see &#39;Successfully connected to the database.&#39;, it means that SQLx was able to connect to our database properly. Good job! Now we&#39;re running our basic Rust code, which is able to connect to our containerized PostgreSQL instance.</p><h3>Summing It Up</h3><p>Okay, I believe this story is long enough for our first tutorial part. By the end of this section, you’ll be able to:</p><ul><li>Set up a PostgreSQL database running in a Docker container.</li><li>Install and use SQLx CLI to create and apply migrations.</li><li>Import and build the main crates that we will use in this project.</li><li>Create a simple connection procedure that retrieves database data from an .env file.</li></ul><p>That’s all for now. In the next part, we’ll create the main routes for our backend to shorten URLs and retrieve the original ones from the shortened versions. I hope you find this starting part clear enough to follow each step. If you appreciate it, don’t forget to clap and follow me for the next tutorial parts.</p><p>See you next time, and thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9babe97b8962" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/crafting-a-rust-url-shortener-part-1-setting-up-your-project-9babe97b8962">Crafting a Rust URL Shortener: Part 1 — Setting Up Your Project</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Must Capture Attention in 7 Seconds]]></title>
            <link>https://medium.com/write-a-catalyst/why-you-must-capture-attention-in-7-seconds-4ff7a8d343d8?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ff7a8d343d8</guid>
            <category><![CDATA[write-a-catalyst]]></category>
            <category><![CDATA[success]]></category>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[medium-partner-program]]></category>
            <category><![CDATA[communication]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 21:21:41 GMT</pubDate>
            <atom:updated>2024-02-08T21:21:41.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EaWVKKCRSOB9bLKA" /><figcaption>Photo by <a href="https://unsplash.com/@frankielopez?utm_source=medium&amp;utm_medium=referral">Frankie Lopez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Research indicates that human attention spans now average just<strong> 8.25 seconds</strong> — less than that of goldfish. To captivate swiftly, articulate the benefits in <strong>7 seconds or fewer</strong>. This timeframe mirrors the average sound bite on TV or radio news, or approximately 23 words in written text.</p><h4>What factors contribute to the shortened attention spans of individuals?</h4><p>Mass media has conditioned people to engage in fleeting bursts of attention.</p><ul><li>Consider the evolution of film shots — from an average of 10 seconds in the 1930s to less than 4 seconds today.</li><li>Even quotes in esteemed publications like The New York Times have decreased in length, with the most common quote now comprising only 7 words.</li><li>On social media platforms like Facebook and LinkedIn, brevity is key, with the optimum post lengths ranging from 9 to 15 words.</li><li>Furthermore, webpage users spend a mere 15 seconds actively engaging with a page</li></ul><h4>What factors contribute to message retention challenges?</h4><p>Neuroscientists term the adversary within your buyers’ minds <em>“habituation.”</em></p><p>Human brains habituate rapidly. Consider common background noises like music, traffic, aircraft, HVAC systems, or even colleagues — they typically fade into the background until brought to one’s awareness.</p><p>Pause for a moment. Can you discern any of these stimuli presently, despite being previously unnoticed? This exemplifies the potency of habituation, which undermines sustained attention.</p><h4>What about our stories on Medium?</h4><p>I’ve applied these concepts to my publications on Medium.com, as well as to articles that pique my interest and compel me to click and jump into their content. We’re all aware that capturing readers’ attention for a minimum of 30 seconds is crucial if we aim to achieve any level of success here. Considering the significance of this timeframe, let’s analyze something about our stories titles.</p><p>Crafting an effective title and subtitle holds paramount importance, as they serve as the initial point of engagement for readers. It’s the first impression your story makes, offering the sole opportunity to captivate and entice individuals to delve into the full narrative — or, at the very least, consider doing so.</p><p>If we aim to navigate the seven-second rule successfully, we must establish a compelling entry point for our stories. That’s precisely what I’d like to discuss today. Every day, I encounter articles on my homepage that resemble this:</p><ul><li>How I Create a $1K Side Hustle in Three Months</li><li>I’ve Recently Landed my 100th Client as an Agency Owner</li><li>My Breakthrough Strategy for Boosting Readership</li></ul><p>Taken out of context, these titles pique our interest, enticing us to delve further into the article. However, it’s become all too common to encounter numerous articles with similar <em>clickbait</em> titles, only to find they offer little substance upon reading. Clickbait has essentially become the <em>‘background noise’</em> I previously mentioned. While I understand the temptation to attract traffic by promising easy solutions such as achieving passive income, the reality is that repetitive, empty articles are causing many readers, myself included, to remove them from our reading lists.</p><p>Having shared my perspective on numerous articles on Medium, I’d like to offer a personal insight based on my experience during my initial two months on the platform. I endeavored to understand why certain articles garnered over a thousand views while others struggled to even reach a hundred. What became apparent from this analysis is that my articles with the lowest performance tended to share two common traits:</p><ul><li>They featured overly technical titles.</li><li>They lacked a compelling subtitle.</li></ul><p>Conversely, my most successful articles exhibit the following common characteristics:</p><ul><li>They articulate a problem and its solution in the title.</li><li>They outline the content readers can anticipate in the subtitle.</li><li>They endeavor to convey insights from a personal perspective.</li></ul><p>While crafting a captivating title and subtitle is crucial, <em>these efforts amount to little if the substance of the article fails to deliver</em>. Unfortunately, many articles seem to exist solely to lure readers in with promises, only to leave them empty-handed after investing their time. This pattern of deception can ultimately be detrimental. Over time, discerning readers will likely distinguish between those who offer meaningful content and those who merely peddle empty promises.</p><p>While my perspective may come across as critical, I sincerely hope you resonate with my sentiments. I’m eager to hear your thoughts on the matter. Thank you for taking the time to read and consider my viewpoint.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff7a8d343d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/write-a-catalyst/why-you-must-capture-attention-in-7-seconds-4ff7a8d343d8">Why You Must Capture Attention in 7 Seconds</a> was originally published in <a href="https://medium.com/write-a-catalyst">Write A Catalyst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super fast http server with Rust + htmx (part 2)]]></title>
            <link>https://levelup.gitconnected.com/super-fast-http-server-with-rust-htmx-part-2-c0398f2a0d42?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0398f2a0d42</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Thu, 08 Feb 2024 01:44:51 GMT</pubDate>
            <atom:updated>2024-02-08T01:44:51.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RkPDbM73bLdpON4YcvTEEA.png" /></figure><p>Welcome to the second part of our tutorial series on creating a super-fast embedded web server with Rust and htmx. If you’ve followed the <a href="https://medium.com/gitconnected/super-fast-http-server-with-rust-htmx-part-1-bfcddbd6e8bc">first part of this tutorial</a>, you might find yourself in a situation where, upon running your server and visiting ‘localhost:8086’ in your browser, you’ll encounter something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*mTXlmiAv9xSwrdQnyKliOA.png" /></figure><p>While if you visit ‘localhost:8086/another-page’, you’ll probably see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*umYsDArPQBTAinKq4dtUIg.png" /></figure><h4>Next Steps</h4><p>Alright, now that both pages are up and running, wouldn’t it be convenient to add a link to navigate between them instead of manually typing the URLs in the browser search bar? Let’s open app.html and make the necessary changes:</p><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}App{% endblock %}<br><br>{% block content %}<br>&lt;div class=&quot;inline-flex flex-row space-x-2&quot;&gt;<br>    &lt;h1 class=&quot;text-indigo-500&quot;&gt;Greetings from the Embedded Web Server!&lt;/h1&gt;<br>    &lt;a<br>        href=&quot;/another-page&quot;<br>        class=&quot;text-red-500 underline hover:text-red-300&quot;<br>        &gt;Another page&lt;/a<br>    &gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><p>If you don’t notice any changes after running your server, it’s because you need to regenerate the necessary CSS resources by running the Tailwind CLI again. As we did in the previous tutorial, you’ll need to execute the following command: npx tailwindcss -i styles/tailwind.css -o assets/main.css --watch.</p><p>Now, let’s also add a simple link to ‘another-page.html’ for navigating back to the main page</p><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}Another page!{% endblock %}<br><br>{% block content %}<br>&lt;div class=&quot;inline-flex flex-row space-x-2&quot;&gt;<br>    &lt;h1 class=&quot;font-bold text-red-500&quot;&gt;Another page&lt;/h1&gt;<br>    &lt;a<br>    href=&quot;/&quot;<br>    class=&quot;text-indigo-500 underline hover:text-indigo-300&quot;<br>    &gt;Main page&lt;/a<br>&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><p>If you’re a fan of dark styles like me, consider adding this to the &lt;body&gt; tag in &#39;base.html&#39;.</p><pre>&lt;body class=&quot;bg-gray-900&quot;&gt;</pre><p>Alright, at this point, we’ve transitioned from an ugly unstyled HTML to an ugly Tailwind-styled HTML. Don’t worry too much about colors for now; once we’ve finished implementing the website functionalities, we can focus on refining the color scheme. Alternatively, feel free to experiment and find the color scheme that works best for you.</p><h4>Integrating htmx into Our Project</h4><p>Having set up our web server to deliver static HTML and enhanced our assets with Tailwind’s styling prowess, we’ve established a solid foundation. Now, let’s complete the web development experience by integrating interactive functionality into our pages using htmx.</p><p>With htmx, we unlock the ability to implement JavaScript-like features seamlessly within our HTML, without the need for complex frameworks. By embracing htmx, we eliminate the need to write custom form handlers or manage AJAX requests manually. Instead, we can focus on delivering a modern user interface experience while leveraging the simplicity of standard hypertext.</p><p>To kick things off, let’s start small by fetching data from an API and dynamically updating elements on the screen. The beauty of htmx lies in its compact size and easy integration into our existing setup. Typically, linking to the htmx library at the top of the page would suffice. However, since our goal is to develop for an embedded solution that may operate without an internet connection for extended periods, we need to take a different approach. This entails manually downloading the htmx library and integrating it into our project.</p><p>You can download htmx from <a href="https://unpkg.com/htmx.org@1.9.10/dist/htmx.min.js">here</a> and save the file as htmx.min.js inside the assets folder of your project. Once saved, simply include the script in your base.html template.</p><pre>&lt;link href=&quot;/assets/main.css&quot; rel=&quot;stylesheet&quot; /&gt;<br>&lt;script src=&quot;/assets/htmx.min.js&quot;&gt;&lt;/script&gt;<br>&lt;!-- Allow any inheriting page to set it&#39;s own title --&gt;<br>&lt;title&gt;{% block title %}{{ title }}{% endblock %}&lt;/title&gt;</pre><p>After including htmx, we’ll proceed to add a button on our homepage. This button will trigger a request to one of our server endpoints to fetch some data. But before we dive into our markup, let’s set up an Axum route that will provide the text data for us to display.</p><pre>let router = Router::new()<br>    .route(&quot;/&quot;, get(hello))<br>    .route(&quot;/another-page&quot;, get(another_page))<br>    .route(&quot;/api&quot;, get(api_sample))<br>    .nest_service(<br>        &quot;/assets&quot;,<br>        ServeDir::new(format!(&quot;{}/assets&quot;, assets_path.to_str().unwrap())),<br>    );<br><br>// all the rest of the code then....<br>// simply return a string from backend<br>async fn api_sample() -&gt; &amp;&#39;static str {<br>    &quot;Hello from Axum backend!&quot;<br>}</pre><p>We’ll now make modifications to the app.html file to display a button on a second line, with the text &#39;Hello Axum?&#39;. Utilizing hx-get, the button will request data from an API endpoint, while hx-swap will prompt htmx to update the button text with the response received from the backend. After saving and running the application, clicking the button triggers this interaction, resulting in the button text dynamically changing to reflect the message retrieved from the preconfigured API endpoint. Voilà!</p><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}App{% endblock %}<br><br>{% block content %}<br>&lt;div class=&quot;inline-flex flex-row space-x-2&quot;&gt;<br>    &lt;h1 class=&quot;text-indigo-500&quot;&gt;Greetings from the Embedded Web Server!&lt;/h1&gt;<br>    &lt;a<br>        href=&quot;/another-page&quot;<br>        class=&quot;text-red-500 underline hover:text-red-300&quot;<br>        &gt;Another page&lt;/a<br>    &gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;mt-4&quot;&gt;<br>    &lt;button<br>        type=&quot;button&quot;<br>        hx-get=&quot;/api&quot;<br>        hx-swap=&quot;innerHtml&quot;<br>        class=&quot;rounded-md bg-indigo-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600&quot;<br>    &gt;<br>        Hello Axum?<br>    &lt;/button&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*IzPuQ1xud85fTQ5BVSmLFQ.png" /></figure><p>Having successfully incorporated htmx into our Askama template and generated CSS with Tailwind, albeit rudimentary in appearance, it’s time to advance further. Our next objective is to dynamically update the template by adding items, akin to a traditional ‘todo list’. To accomplish this, we’ll leverage a handy Tailwind plugin designed to enhance the visual aesthetics of our inputs.</p><pre>npm add -D @tailwindcss/forms</pre><p>Once that’s installed, let’s update our tailwind.config.cjs file:</p><pre>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [&#39;./templates/*.html&#39;],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [require(&#39;@tailwindcss/forms&#39;)],<br>}</pre><p>Ok now we can create another template called todo-form.html:</p><pre>&lt;div class=&quot;mt-3&quot;&gt;<br>    &lt;form<br>    hx-post=&quot;/todos&quot;<br>    hx-target=&quot;#todos&quot;<br>    hx-swap=&quot;innerHTML&quot;<br>    class=&quot;max-w-md border-t-2 border-gray-600 py-2&quot;<br>    &gt;<br>    &lt;label for=&quot;todo&quot; class=&quot;block text-sm font-medium leading-6 text-gray-300&quot;<br>    &gt;Todo List&lt;/label<br>    &gt;<br>    &lt;div class=&quot;mt-2 inline-flex flex-row space-x-2 bg-gray-900&quot;&gt;<br>        &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;todo&quot;<br>        id=&quot;todo&quot;<br>        class=&quot;block w-full rounded-md border-0 py-1.5 bg-gray-900 text-gray-300 shadow-sm ring-1 ring-inset ring-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-gray-400 sm:text-sm sm:leading-6&quot;<br>        placeholder=&quot;Replace frontend with htmx&quot;<br>        /&gt;<br>        &lt;button<br>        type=&quot;submit&quot;<br>        class=&quot;rounded-md bg-cyan-600 px-2.5 py-1.5 text-sm font-semibold text-gray-200 shadow-sm hover:bg-cyan-300 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-400&quot;<br>        &gt;<br>        Add<br>    &lt;/button&gt;<br>&lt;/div&gt;<br>&lt;/form&gt;<br>&lt;div id=&quot;todos&quot; /&gt;<br>&lt;/div&gt;</pre><p>We’ve enhanced our HTML with htmx directives, leveraging hx-post, hx-target, and hx-swap functionalities:</p><ul><li>hx-post guides our form submission to the specified endpoint via a POST request.</li><li>hx-target designates the element we wish to modify following the response.</li><li>hx-swap=&quot;innerHTML&quot; signifies that the HTML content returned from our add_todo handler will replace the existing content within the &lt;div id=&quot;todos&quot; /&gt; tag.</li></ul><p>We must now maintain our todos in a vector to display them when adding new ones. To achieve this, we’ll introduce an AppState, combining an Arc and Mutex, allowing Axum to share these values across tasks. In our main.rs</p><pre>struct AppState {<br>    todos: Mutex&lt;Vec&lt;String&gt;&gt;,<br>}<br>//<br>//<br>#[tokio::main]<br>async fn main() -&gt; anyhow::Result&lt;()&gt; {<br>// other code</pre><p>Then we istantiate it:</p><pre>let app_state = Arc::new(AppState {<br>        todos: Mutex::new(vec![]),<br>    });<br>//<br>//<br>info!(&quot;router init...&quot;);</pre><p>We need to add a new route for todo stuff and add state to our router passing it our app_state:</p><pre>let router = Router::new()<br>        .route(&quot;/&quot;, get(hello))<br>        .route(&quot;/another-page&quot;, get(another_page))<br>        .route(&quot;/api&quot;, get(api_sample))<br>        .route(&quot;/todos&quot;, post(add_todo))<br>        .nest_service(<br>            &quot;/assets&quot;,<br>            ServeDir::new(format!(&quot;{}/assets&quot;, assets_path.to_str().unwrap())),<br>        ).with_state(app_state);</pre><p>Now let’s add the add_todo function, to be able to extract our todo from the form input text, and push it into the app_state String vector:</p><pre>#[derive(Template)]<br>#[template(path = &quot;todo-list.html&quot;)]<br>struct TodoList {<br>    todos: Vec&lt;String&gt;,<br>}<br><br>#[derive(Deserialize)]<br>struct FormData {<br>    todo: String,<br>}<br><br>async fn add_todo(<br>    State(state): State&lt;Arc&lt;AppState&gt;&gt;,<br>    Form(form_data): Form&lt;FormData&gt;,<br>) -&gt; impl IntoResponse {<br>    let mut lock = state.todos.lock().unwrap();<br>    lock.push(form_data.todo);<br><br>    let template = TodoList {<br>        todos: lock.clone(),<br>    };<br><br>    HtmlTemplate(template)<br>}</pre><p>As you can observe, we have derived a template named todo-list.html, which has not been created yet. This template will serve as the component responsible for displaying the todos, and it will dynamically update each time a new string is pushed into the vector. The function returns the template, and as demonstrated earlier, utilizing htmx, the returned content will be rendered within the div element identified by the id ‘todos’, which we have positioned at the bottom of our form component.</p><p>So, let’s create a new template file called todo-list.html and and write this code:</p><pre>{% for todo in todos %}<br>&lt;p class=&quot;text-lg text-gray-200&quot;&gt;{{ todo }}&lt;/p&gt;<br>{% endfor %}</pre><p>This code is pretty straightforward, it adds a paragraph for each todo into the vector returned by axum. Now, I’d like to refine the older HTML from part 1 to achieve a more uniform, albeit rudimentary, style. Let’s make some CSS adjustments to both app.html and another-page.html.</p><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}App{% endblock %}<br><br>{% block content %}<br>&lt;div class=&quot;inline-flex flex-row space-x-2&quot;&gt;<br>    &lt;h1 class=&quot;text-gray-200&quot;&gt;Greetings from the Embedded Web Server!&lt;/h1&gt;<br>    &lt;a<br>        href=&quot;/another-page&quot;<br>        class=&quot;text-gray-400 underline hover:text-gray-300&quot;<br>        &gt;Another page&lt;/a<br>    &gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;my-4&quot;&gt;<br>    &lt;button<br>        type=&quot;button&quot;<br>        hx-get=&quot;/api&quot;<br>        hx-swap=&quot;innerHtml&quot;<br>        class=&quot;rounded-md bg-cyan-600 px-2.5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-cyan-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-600&quot;<br>    &gt;<br>        Hello Axum?<br>    &lt;/button&gt;<br>&lt;/div&gt;<br>{% include &quot;todo-form.html&quot; %}<br>{% endblock %}</pre><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}Another page!{% endblock %}<br><br>{% block content %}<br>&lt;div class=&quot;inline-flex flex-row space-x-2&quot;&gt;<br>    &lt;h1 class=&quot;font-bold text-gray-200&quot;&gt;Another page&lt;/h1&gt;<br>    &lt;a<br>    href=&quot;/&quot;<br>    class=&quot;text-gray-400 underline hover:text-gray-300&quot;<br>    &gt;Main page&lt;/a<br>&gt;<br>&lt;/div&gt;<br>{% endblock %}</pre><p>Now, assuming your compiler doesn’t present any errors, you should see a display resembling the image below. You’ll then be able to input text into the todo form and see it appended to the list below. Wonderful!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tO744PV88Gq9kM-jnC8G8w.png" /></figure><h4>In Conclusion</h4><p>It’s been quite a journey, starting from scratch in <a href="https://medium.com/gitconnected/super-fast-http-server-with-rust-htmx-part-1-bfcddbd6e8bc">Part 1</a>, to achieving a simple yet functional frontend feature by the end of Part 2. While the styling may not be extraordinary, the goal of these tutorials was to equip you with the tools to create a fully functional Axum backend, harnessing the capabilities of Askama and htmx, and seamlessly integrating with one of the best CSS frameworks, Tailwind. Be sure to check out the <a href="https://github.com/deid84/rust-htmx">GitHub</a> repository, as I’ll be adding more detailed comments to the code in the coming days to provide a clearer understanding of the steps involved.</p><p>I hope you found this tutorial helpful, and don’t forget to show your support by clapping or following me for more tutorials like this. Thank you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0398f2a0d42" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/super-fast-http-server-with-rust-htmx-part-2-c0398f2a0d42">Super fast http server with Rust + htmx (part 2)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super fast http server with Rust + htmx (part 1)]]></title>
            <link>https://levelup.gitconnected.com/super-fast-http-server-with-rust-htmx-part-1-bfcddbd6e8bc?source=rss-98c59e5e0a43------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfcddbd6e8bc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[htmx]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Davide Ferrero]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 14:14:50 GMT</pubDate>
            <atom:updated>2024-02-09T07:09:31.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*O2thZid3e88MjOVl2Dq1HQ.png" /></figure><p><a href="https://medium.com/gitconnected/cross-compile-your-rust-app-for-multiple-architectures-069bf98d0728">In one of my first articles</a>, I talked about the use of <strong>Rust</strong> across various architectures. Given my role in working with embedded Linux systems, it becomes imperative to employ an efficient programming language that optimally utilizes the available hardware resources. While my previous discussion focused on the simplicity of cross-compilation in Rust, it represents only the initial phase of the process.</p><p>In the context of my work, a common requirement is to provide customers with an interface for managing their devices. This aspect can be aptly termed as an embedded web server.</p><p>If you scour the web in search of information on this topic, you’ll come across a plethora of interesting articles and tutorials. The issue, however, is that almost 90% of these resources provide excellent solutions tailored for hardware much more powerful than mine. Typically, they delve into:</p><ol><li>The separation of backend and frontend.</li><li>The utilization of microservices architecture.</li><li>The implementation of message brokers.</li><li>The use of sophisticated databases.</li></ol><p>While these aspects are fundamental in server deployments, they might be overkill for an embedded Linux solution. Recognizing this, I began exploring htmx last month with the aim of designing something more lightweight, ensuring a decent user experience within the constraints of embedded web servers. Today, I would like to share what I’ve learned and discuss my ideas for future implementations.</p><h4>The Stack</h4><p>To get started, let’s go over the components we’ll use to construct a relatively simple application. This application will serve static HTML but with reactivity powered by htmx. Our sandbox setup will resemble something like:</p><ul><li><strong>Rust:</strong> (can you believe it?)</li><li><strong>Axum:</strong> To serve static assets and power the backend API</li><li><strong>Askama:</strong> For HTML templating, facilitating shared layouts, scripts, CSS, etc.</li><li><strong>htmx:</strong> For reactivity on the UI.</li><li><strong>Tailwind:</strong> Because embedded doesn’t mean ugly, right?</li></ul><h4>First Setup</h4><p>First we’ll add the necessary dependencies to our Cargo.toml file.</p><pre>[package]<br>name = &quot;rust-htmx&quot;<br>authors = [&quot;Davide Ferrero&quot;]<br>description = &quot;Rust-Axum-Askama-HTMX: Crafting a Lightweight Embedded Web Server&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[dependencies]<br>anyhow = &quot;1.0.79&quot;<br>askama = &quot;0.12.1&quot;<br>axum = &quot;0.7.4&quot;<br>tokio = { version = &quot;1.36.0&quot;, features = [&quot;full&quot;] }<br>tower = &quot;0.4.13&quot;<br>tower-http = { version = &quot;0.5.1&quot;, features = [&quot;fs&quot;] }<br>tracing = &quot;0.1.40&quot;<br>tracing-subscriber = { version = &quot;0.3.18&quot;, features = [&quot;env-filter&quot;] }</pre><p>I also recommend installing cargo-watch for the convenience of the hot reload feature, eliminating the need to type &#39;cargo run&#39; each time you want to see changes. To install it globally, simply use &#39;cargo install cargo-watch&#39;. Once installed, you can run it with &#39;cargo-watch -x run&#39;.</p><p>Now we’re ready to run cargo build to download and compile all dependencies. While compiling, you can set up and configure the tracer in the main.rs file.</p><pre>use tracing::info;<br>use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};<br><br>#[tokio::main]<br>async fn main() {<br>    tracing_subscriber::registry()<br>        .with(<br>            tracing_subscriber::EnvFilter::try_from_default_env()<br>                .unwrap_or_else(|_| &quot;rust_htmx=debug&quot;.into()),<br>        )<br>        .with(tracing_subscriber::fmt::layer())<br>        .init();<br><br>    info!(&quot;Embedded Web Server says: Hello, World!&quot;);<br>}</pre><p>If you&#39;ve never used the tracer before, take note that, despite my app being named &#39;rust-htmx&#39;, you should use &#39;rust_htmx&#39; in the EnvFilrer. If you run the app you should see something like this:</p><pre>   Compiling rust-htmx v0.1.0 (C:\Users\davide.ferrero\Documents\Rust\rust-htmx)<br>    Finished dev [unoptimized + debuginfo] target(s) in 1.88s<br>     Running `target\debug\rust-htmx.exe`<br>2024-02-05T14:54:56.118052Z  INFO rust_htmx: Embedded Web Server says: Hello, World!</pre><p>Now inmain.rs, let&#39;s add an axum route to serve askama template.</p><pre>use anyhow::Context;<br>use askama::Template;<br>use axum::{<br>    http::StatusCode,<br>    response::{Html, IntoResponse, Response},<br>    routing::get,<br>    Router,<br>};<br>use tracing::info;<br>use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};<br><br>#[tokio::main]<br>async fn main() -&gt; anyhow::Result&lt;()&gt; {<br>    tracing_subscriber::registry()<br>        .with(<br>            tracing_subscriber::EnvFilter::try_from_default_env()<br>                .unwrap_or_else(|_| &quot;rust_htmx=debug&quot;.into()),<br>        )<br>        .with(tracing_subscriber::fmt::layer())<br>        .init();<br><br>    info!(&quot;router init...&quot;);<br><br>    let router = Router::new().route(&quot;/&quot;, get(hello));<br>    let port = 8086_u16;<br>    let listener = tokio::net::TcpListener::bind(format!(&quot;0.0.0.0:{}&quot;, port))<br>        .await<br>        .unwrap();<br><br>    info!(&quot;router init complete: now listening on port {}&quot;, port);<br><br>    axum::serve(listener, router).await.unwrap();<br><br>    Ok(())<br>}<br><br>async fn hello() -&gt; impl IntoResponse {<br>    let template = HelloTemplate {};<br>    HtmlTemplate(template)<br>}<br><br>#[derive(Template)]<br>#[template(path = &quot;app.html&quot;)]<br>struct HelloTemplate;<br><br>/// A wrapper type that we&#39;ll use to encapsulate HTML parsed by askama into valid HTML for axum to serve.<br>struct HtmlTemplate&lt;T&gt;(T);<br><br>/// Allows us to convert Askama HTML templates into valid HTML for axum to serve in the response.<br>impl&lt;T&gt; IntoResponse for HtmlTemplate&lt;T&gt;<br>where<br>    T: Template,<br>{<br>    fn into_response(self) -&gt; Response {<br>        // Attempt to render the template with askama<br>        match self.0.render() {<br>            // If we&#39;re able to successfully parse and aggregate the template, serve it<br>            Ok(html) =&gt; Html(html).into_response(),<br>            // If we&#39;re not, return an error or some bit of fallback HTML<br>            Err(err) =&gt; (<br>                StatusCode::INTERNAL_SERVER_ERROR,<br>                format!(&quot;Failed to render template. Error: {}&quot;, err),<br>            )<br>                .into_response(),<br>        }<br>    }<br>}</pre><p>At this point, you may encounter an error after the hello function. This is because Askama searches for a app.html file in the templates folder, but both these components are currently absent. To resolve this, create a folder in the root directory called templates and inside it, create a file named app.html. Feel free to add any content you&#39;d like; for example, I wrote &lt;h1&gt;Greetings from the Embedded Web Server&lt;/h1&gt;. If you run the code now, you should observe a similar outcome under localhost:8086.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*XGLQj-GKoYi_i3JzBosl5Q.png" /></figure><p>Now, looking at our page, it’s clear there’s room for improvement. Let’s enhance its appearance and bring it into the present. My tool of choice is <strong>Tailwind</strong>, mainly because of its extensive utility.</p><p><strong>Tailwind</strong> provides integration guides for various tech stacks, but unfortunately, <em>Rust-based static file serving with Axum</em> isn’t covered. No worries, though — we can rely on basic Tailwind strategies to introduce some styling.</p><p>If you’re not familiar with Tailwind, <a href="https://tailwindcss.com/">refer to the documentation</a> and understand its design system philosophy. We’ll leverage optimizations, and one key advantage is <a href="https://tailwindcss.com/docs/optimizing-for-production">Tailwind’s ability to minimize CSS</a>, ensuring our bundled styles remain compact.</p><p>We now need to create a simple package.json file in the root folder of our project to integrate Tailwind into our project, typing npm init</p><pre>{<br>  &quot;name&quot;: &quot;rust-htmx&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;description&quot;: &quot;Rust-Axum-Askama-HTMX: Crafting a Lightweight Embedded Web Server&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;author&quot;: &quot;Davide Ferrero&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;<br>}</pre><p>With our package manifest set up, let’s proceed to make a few additions to it.</p><pre>npm add -D tailwindcss prettier prettier-plugin-tailwindcss</pre><p>Now, we can refine our JSON by removing unnecessary parts and adding a quick script for linting purposes.</p><pre>{<br>  &quot;name&quot;: &quot;rust-htmx&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;format&quot;: &quot;prettier --write --ignore-unknown .&quot;<br>  },<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;prettier&quot;: &quot;^3.2.5&quot;,<br>    &quot;prettier-plugin-tailwindcss&quot;: &quot;^0.5.11&quot;,<br>    &quot;tailwindcss&quot;: &quot;^3.4.1&quot;<br>  }<br>}</pre><p>Now that we can format the code by running npm run format from the terminal, let&#39;s return to our app.html file and make some additions. Don&#39;t be concerned about the non-existent main.css at the top of the file; this CSS file will store the compiled output that Tailwind’s CLI generates. The CLI scans the HTML files in our /templates directory, identifying and excluding unnecessary utility classes. This optimization aids in minimizing the size of the bundled CSS file that will be delivered to our users’ browsers.</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;link href=&quot;/assets/main.css&quot; rel=&quot;stylesheet&quot; /&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;h1 class=&quot;text-indigo-500&quot;&gt;Greetings from the Embedded Web Server!&lt;/h1&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>As mentioned earlier, this will be a generated file and might not be included by default. To start, we have to add a CSS file that Tailwind will utilize to generate the utilities used in our HTML templates. Let’s create a file named tailwind.css in the styles directory:</p><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><p>We’ll utilize the CLI to read the tailwind.css file as input, analyze the utilities employed in our HTML, and generate the optimized stylesheet for serving. Let&#39;s initiate our first pass:</p><pre>npx tailwindcss -i styles/tailwind.css -o styles/main.css --watch<br><br>Rebuilding...<br><br>warn - No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.<br>warn - https://tailwindcss.com/docs/content-configuration<br><br>Done in 182ms.</pre><p>Good progress! However Tailwind didn’t detect any utility classes to purge. This is because we don’t have a configuration file for it to read and guide its analysis of the markup. Let’s add one:</p><pre>npx tailwindcss init     <br><br>Created Tailwind CSS config file: tailwind.config.js</pre><p>And do some minor changes to the generated file:</p><pre>/** @type {import(&#39;tailwindcss&#39;).Config} */<br>module.exports = {<br>  content: [&#39;./templates/*.html&#39;],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>}</pre><p>I’ll also rename the extension to .cjs to ensure compatibility with ESLint. For those unfamiliar with Tailwind, this is essentially a configuration file instructing Tailwind where to locate utility classes for tree-shaking ones we’re not using. Now, returning to our main.rs file, we need to instruct Axum to serve our Tailwind-compiled CSS file from the &#39;assets&#39; folder through a Tower service route.</p><pre>// Add assets to router<br>let assets_path = std::env::current_dir().unwrap();<br>let router = Router::new().route(&quot;/&quot;, get(hello)).nest_service(<br>    &quot;/assets&quot;,<br>    ServeDir::new(format!(&quot;{}/assets&quot;, assets_path.to_str().unwrap())),<br>);</pre><p>If we run Tailwind CLI again it will update the main.css file and if you reload the page you’ll finally see the h1 block with indigo colour.</p><h4>Extending Template Structure</h4><p>Our current template generation system lacks a crucial element: template inheritance. If we were to introduce additional axum routes serving HTML, we would be faced with the inconvenience of including &lt;head&gt; tags for each file. This isn&#39;t an optimal developer experience, as ideally, we&#39;d like our templates to extend a base markup file containing all common head metadata such as links and tags.</p><p>Fortunately, Askama provides a solution to this issue through template inheritance. We can define base template layouts that individual route templates will extend. To streamline our development process and avoid duplicating boilerplate HTML in every template, let’s create a base.html file. This file will serve as the foundation, including all shared head metadata for a cohesive and efficient approach.</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>    &lt;head&gt;<br>        &lt;link href=&quot;/assets/main.css&quot; rel=&quot;stylesheet&quot; /&gt;<br>        &lt;link href=&quot;https://rsms.me/inter/inter.css&quot; rel=&quot;stylesheet&quot; /&gt;<br>        &lt;!-- Allow any inheriting page to set it&#39;s own title --&gt;<br>        &lt;title&gt;{% block title %}{{ title }}{% endblock %}&lt;/title&gt;<br><br>        &lt;!-- Allow any inheriting page to extend head with additional assets --&gt;<br>        {% block head %}{% endblock %}<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div id=&quot;content&quot;&gt;<br>            &lt;!-- Inheriting pages will have their content rendered here, similar to app root in React, Angular, etc. --&gt;<br>            {% block content %}{% endblock %}<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now we can clean our app.html as follows:</p><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}App{% endblock %}<br><br>{% block content %}<br>&lt;h1 class=&quot;text-indigo-500&quot;&gt;Greetings from the Embedded Web Server!&lt;/h1&gt;<br>{% endblock %}</pre><p>To prove that we’ve now got a nice extendable page model, let’s add another page with a link on our home page that routes to this new page that I’ll cleverly name /another-page with its even more cleverly associated template another-page.html:</p><pre>&lt;!-- prettier-ignore --&gt;<br>{% extends &quot;base.html&quot; %}<br><br>{% block title %}Another page!{% endblock %}<br><br>{% block content %}<br>&lt;h1 class=&quot;font-bold text-red-500&quot;&gt;Another page&lt;/h1&gt;<br>{% endblock %}</pre><p>Now, let’s incorporate an Axum route to handle requests for this template when users access the /another-page frontend route.</p><pre>let router = Router::new()<br>    .route(&quot;/&quot;, get(hello))<br>    .route(&quot;/another-page&quot;, get(another_page))<br>    .nest_service(<br>        &quot;/assets&quot;,<br>        ServeDir::new(format!(&quot;{}/assets&quot;, assets_path.to_str().unwrap())),<br>    );<br><br>........<br><br>async fn another_page() -&gt; impl IntoResponse {<br>    let template = AnotherPageTemplate {};<br>    HtmlTemplate(template)<br>}<br><br>#[derive(Template)]<br>#[template(path = &quot;another-page.html&quot;)]<br>struct AnotherPageTemplate;</pre><p>If you had stopped the Tailwind CLI earlier, be sure to restart it to update the main.css file with the recently added styles. Afterward, if you manually navigate to another page in the localhost path, you should now see the second page styled in red. Wonderful!</p><h4>Next steps</h4><p>That’s all for today! <a href="https://levelup.gitconnected.com/super-fast-http-server-with-rust-htmx-part-2-c0398f2a0d42">In the next segment</a>, we’ll begin incorporating navigation capabilities and implementing some exciting htmx features to enhance our simple app. If you prefer to download the repository directly, <a href="https://github.com/deid84/rust-htmx">here’s the link to get started</a>. I hope you found this initial part interesting, and if you encounter any challenges or have questions, don’t hesitate to reach out. Until next time, thank you, and see you in the next session!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfcddbd6e8bc" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/super-fast-http-server-with-rust-htmx-part-1-bfcddbd6e8bc">Super fast http server with Rust + htmx (part 1)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>