Go Summarize

Rust Axum Full Course - Web Development (GitHub repo updated to Axum 0.7)

Jeremy Chone2023-04-09
Rust Programming#Tutorial#Web Development
115K views|1 years ago
💫 Short Summary

The video tutorial provides a comprehensive guide on developing with the Axum web framework for REST. It covers beginner to advanced topics such as setting up a server, creating routes, handling requests, and implementing error handling. Key steps include creating routers, handling parameters, building handlers, and implementing middleware for authentication and error management. The tutorial emphasizes structuring code effectively, optimizing middleware for efficiency, and handling errors securely. It concludes with insights into logging, monitoring, and advancing from beginner to advanced levels in utilizing the Axum framework.

✨ Highlights
📊 Transcript
✦
Overview of Axum web framework for REST.
00:00
Covers beginner, intermediate, and advanced topics such as setting up a server, creating routes, handling requests, and starting the server.
Key steps include adding Axum, creating routers, defining routes, starting the server, and testing on localhost.
Emphasizes the importance of following steps carefully to successfully set up an Axum server and receive a 'hello world' response.
Provides a comprehensive guide for developing with Axum.
✦
Setting up a router for quick server development.
03:04
Creating a quick Dev environment with cargo test.
Adding HTTP client testing libraries and setting up a base URL.
Compiling and running the server with cargo watch for efficient development.
Testing the client side with cargo test and creating a Handler function for responses.
✦
Passing parameters to a URL using struct and query extractors.
08:35
Creating a struct for parameters and extracting query parameters into the function.
Mapping function arguments to URL query parameters and formatting output without new allocations.
Modifying code in a quick Dev terminal and successfully testing the changes.
Gratitude expressed to a sponsor and encouragement for support on Patreon.
✦
Building a Handler function and implementing static routing using Axum.
10:37
Composing multiple routers using the merge function.
Utilizing Nest service for static file routing.
Mapping UI errors to domain names and serving directories with pre-built services.
Highlighting the componentized nature of Axum and its use of Tower for services like serving directories.
✦
Importing tower.htp and utilizing FS for file system in ML in the Tower ecosystem for service infrastructure APIs.
12:09
Setting up a login API and creating an error module.
Implementing trait of axon for error response and emphasizing the importance of IntoResponse trait for error handling.
Consuming itself to return a response in axon type for future use.
✦
Importance of handling server errors internally to avoid security risks.
15:16
Emphasis on the need for a secure and organized approach to error handling within modules.
Creating a structured web layer starting with a login API and defining the payload to be sent from the client.
Implementing a login handler function and utilizing a JSON body extractor for processing login payloads.
✦
Implementation of database authentication logic and creating a basic API login handler with hard-coded credentials.
18:27
Setting up routing in the application, including creating a success response body and handling login failures.
Integrating cookie functionality for session management and following best practices for code structuring.
Testing the API login functionality reveals server errors and successful login responses, showing progress in development.
✦
Adding a special layer as an async function in Axon for response mapping.
21:55
The layer can modify or return the response from the router.
Importance of main response mapper in error handling for servers and clients.
Adding middleware into the router using the layer method, specifically 'map response'.
Detailed process of adding cookies to login functionality and the execution order of layers in middleware.
✦
Implementing a REST API with a focus on the model layer.
24:34
The architecture involves web event handlers, middleware, and models.
A mock model layer is created with a simple design and in-memory store.
The goal is to have a flexible model interface that can swap out the store layer easily.
Topics covered include creating error and result pairs, defining data types for tickets, and addressing serialization and debugging needs for data storage and retrieval.
✦
Creating JSON payloads for client communication and structuring a 'ticket for create' payload.
26:29
Disallowing certain fields for security reasons and implementing the model-controller pattern for managing data.
Emphasizing simplicity in initial implementation, including using an in-memory store for tickets and incorporating mutex for exclusive access.
Deriving application state from clones and implementing a basic async constructor for handling ticket store access.
Highlighting the importance of controlling constructor signature early on for future flexibility.
✦
Implementation of 'create' method in ticket creation.
29:17
Tutorial focuses on asynchronous creation of tickets and storing them in a mutable array.
Process includes locking, unwrapping, and working with IDs and titles for ticket creation.
Touches on cloning tickets, filtering out deleted items, and importance of correct intent.
Brief mention of implementing 'delete' functionality with emphasis on mutability and error handling.
✦
Creating a model layer in a web application.
32:06
Error handling is added for ticket deletion with a defined error message for ticket not found as a struct variant.
A web layer is created by adding a sub-module for ticket routes.
Rest handlers are created and the model layer is simplified, with shared state across all handlers.
A Json body extractor is set up for ticket creation, and the segment ends with discussing returning ticket data and listing tickets.
✦
Creating a delete function in the model layer for a JSON ticket in a REST API.
34:20
Using the model controller state and ID in the path for the REST API.
Creating a router with routes for tickets and ticket IDs, including handlers for post, get, delete, and update operations.
Passing multiple states using a struct with sub-states.
Implementing the 'from_ref' macro to easily inject sub-states in the route for effective functioning of existing bindings in the rest handler.
✦
Initializing a Model Controller in Rust Programming.
37:25
The segment covers creating a new model controller and merging REST APIs.
Routes are prefixed with 'slash API' and various operations like creating and listing tickets are executed.
Demonstrates deleting a ticket and handling errors for non-existent tickets.
Provides insights into structuring and managing APIs effectively with Rust programming.
✦
Implementing custom middleware for authentication in a web module.
40:40
Creation of a sub-module named 'MW_auth' to handle authentication-related tasks.
Middleware functions check for cookie existence, utilize tokens, and handle authentication requirements.
By implementing middleware, users can require login credentials for accessing or saving data, enhancing security measures.
Middleware provides power and flexibility in managing requests and responses, allowing for customization and control over authentication processes.
✦
Implementation of middleware authentication in a route API.
43:41
Testing shows successful API requests with proper login activation, including post and get requests.
Debug print statements added for monitoring authentication calls.
Implementation appears to be working well, with token passing and authentication functioning smoothly in the system.
✦
Overview of passing tokens in a specific format using regex and a lazy regex library.
46:15
Creating a path token and capturing regex from the lazy regex library for efficient compilation and reuse.
Error handling and user ID validation as part of the token creation process.
Emphasis on token component validation to ensure user ID, expression, and signature match.
Mention of the need for specific frameworks and upcoming videos on the topic.
✦
Implementation of context module for user ID extraction in middleware authentication.
49:07
Context module created for user ID security and access control.
Context struct includes user ID and implements clone for pass across threads.
Constructor design pattern used to create context, ensuring user ID integrity.
Property accessors used for user ID retrieval and implementation of CTX extractor in middleware authentication.
✦
Implementing async functions in Rust using the 'async trait' requires the use of 'cargo toml' and 'import async trait' crate.
52:36
Information extraction from headers, especially cookies, is done through specific extractors.
Defining an error type and implementing the async function from request parts are part of the process.
The video mentions the use of 'async trait macro' and 'CTX' for error handling.
Flexibility in injecting extractors and code simplification are highlighted in the conclusion after implementation.
✦
Highlights of CTX Extractor Utilization
54:44
The CTX extractor maintains behavior across rods for universal use.
Understanding how the extractor works is crucial for consistent functionality in all rods.
Implementing CTX in handlers aids in error detection when not utilized correctly.
Future utilization of CTX includes access control and privileges in the model layer, enhancing security.
✦
Implementing model controller CRUD operations, adding CTX for authorization, and optimizing middleware for efficiency.
57:31
CTX resolver middleware utilizes extractors like cookies and model controllers.
Importance of optimizing token component validation using cookie middleware.
Emphasis on using match for synchronous operations and preparing code for future scalability.
Reminder to choose coding practices that work best for individual needs.
✦
Cleaning up cookies in a function for proper client handling.
01:00:36
Removal of cookies if there is a CTX error that does not match the necessary token cookie.
Storing CTX result in the request extension using a trick involving request extension mute.
Simplifying the extractor and converting an option into a result to handle errors effectively.
Emphasis on error handling and cloning error types for proper functioning.
✦
Creating a middleware with a cookie extractor above the cookie manager layer is discussed in the segment.
01:03:59
Emphasis is placed on the significance of error handling and capturing errors in middlewares and handlers.
Additional information can be added to server and client errors using strum macros and uid.
Variants of client errors like login fail, no auth, and invalid params are defined in snake case.
The utilization of strum macros to centralize variants as strings for API results is explained.
✦
Implementing custom error handling in a server-client setup.
01:06:40
The process involves converting server errors to client errors through a custom implementation.
Various error types such as server error, auth error, and login fail are tackled with specific status codes.
Handling errors securely is crucial to prevent sensitive information exposure to hackers.
Fallback responses and allowing unreachable patterns for error handling are discussed, stressing the importance of thorough error handling and placeholder responses.
✦
The segment focuses on utilizing a macro from Strum to convert variant name to a string and creating a UUID for server-client error matching.
01:08:50
Client errors are handled by constructing a new response and integrating it into Turbo.
The use of 'As ref' is explained, highlighting how it copies the status code.
The process ends with logging the server log line and returning the error response if needed.
✦
Setting up server to print server errors, debugging client errors, and building a server log line.
01:11:57
Emphasizes the importance of request log lines for debugging and monitoring in the cloud.
Creating a log mode, inserting a city whiz extension, and constructing a flat request log line with various attributes like error data, HTTP request details, user ID, and timestamp.
The ultimate goal is to serialize this data into newline JSON for flexibility and efficient querying in tools like Cloudwatch.
✦
Implementing a log request function for error handling and monitoring purposes.
01:15:05
The function gathers information such as UID, request method, URI, CTX, service error, and client error.
It builds a request log line and handles error data serialization to Json.
Emphasizes the importance of capturing and mapping various data types for error handling and logging.
The logged information is sent to a cloud watch service for monitoring.
✦
Extracting information with XM and the extractors for building a request log line.
01:18:13
Unzipping for client error extraction by selecting the desired error option and logging the client error type.
Ensuring smooth operation and accurate data logging for production applications.
Advancement from beginner to advanced levels in utilizing the web framework through these steps.
Encouragement for continued learning and coding progress.