### Quick Start GURT Server
Source: https://docs.gurted.com/docs/gurt-server
A basic example of setting up and running a GURT server. It initializes tracing, creates a server with TLS certificates, defines two routes ('/' and '/api/users'), and starts listening on a specified address.
```rust
use gurt::prelude::*;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let server = GurtServer::with_tls_certificates("cert.pem", "key.pem")?
.get("/", |_ctx| async {
Ok(GurtResponse::ok().with_string_body("
Hello, GURT!
"))
})
.get("/api/users", |_ctx| async {
let users = json!(["Alice", "Bob"]);
Ok(GurtResponse::ok().with_json_body(&users))
});
println!("GURT server starting on gurt://127.0.0.1:4878");
server.listen("127.0.0.1:4878").await
}
```
--------------------------------
### Quick Start: Make a GET Request with GURT Client
Source: https://docs.gurted.com/docs/gurt-client
A basic example demonstrating how to initialize the GURT client and make a GET request to a GURT server. It prints the status code and body of the response.
```Rust
use gurt::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let client = GurtClient::new();
// Make a GET request
let response = client.get("gurt://example.com/").await?;
println!("Status: {}", response.status_code);
println!("Body: {}", response.text()?);
Ok(())
}
```
--------------------------------
### Serve with Manual Setup (No Config File)
Source: https://docs.gurted.com/docs/gurty-cli
Starts the gurty server manually specifying certificate and key files, and a directory for serving content. This bypasses the need for a configuration file.
```bash
gurty serve --cert localhost+2.pem --key localhost+2-key.pem --dir ./public
```
--------------------------------
### Install GURT and Tokio
Source: https://docs.gurted.com/docs/gurt-server
Add the GURT library and Tokio runtime to your project's Cargo.toml file for managing dependencies. This setup is essential for running the GURT server.
```toml
[dependencies]
gurt = "0.1"
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
tracing-subscriber = "0.3"
serde_json = "1.0"
```
--------------------------------
### Start GURT server with certificates
Source: https://docs.gurted.com/docs/gurt-protocol
Starts the GURT server using the 'gurty serve' command, specifying the generated certificate and private key files for secure communication.
```bash
gurty serve --cert localhost+2.pem --key localhost+2-key.pem
```
--------------------------------
### Serve with Explicit Certificates and Configuration
Source: https://docs.gurted.com/docs/gurty-cli
Starts the gurty server using explicit certificate and key files along with a TOML configuration file. This is useful for custom SSL setups.
```bash
gurty serve --cert localhost+2.pem --key localhost+2-key.pem --config gurty.toml
```
--------------------------------
### Build GURT API Client in Rust
Source: https://docs.gurted.com/docs/gurt-client
This comprehensive example demonstrates building a GURT API client in Rust. It defines data structures for user creation and retrieval, implements methods for creating and getting users via a GURT API, and includes a main function to execute these operations.
```Rust
use gurt::prelude::*;
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
struct CreateUser {
name: String,
email: String,
}
#[derive(Deserialize)]
struct User {
id: u64,
name: String,
email: String,
}
struct ApiClient {
client: GurtClient,
base_url: String,
}
impl ApiClient {
fn new(base_url: String) -> Self {
Self {
client: GurtClient::new(),
base_url,
}
}
async fn create_user(&self, user: CreateUser) -> Result {
let url = format!("{}/users", self.base_url);
let response = self.client.post_json(&url, &user).await?;
if !response.is_success() {
return Err(GurtError::invalid_message(
format!("API error: {}", response.status_message)
));
}
let user: User = serde_json::from_slice(&response.body)?;
Ok(user)
}
async fn get_user(&self, id: u64) -> Result {
let url = format!("{}/users/{}", self.base_url, id);
let response = self.client.get(&url).await?;
if response.status_code == 404 {
return Err(GurtError::invalid_message("User not found".to_string()));
}
if !response.is_success() {
return Err(GurtError::invalid_message(
format!("API error: {}", response.status_message)
));
}
let user: User = serde_json::from_slice(&response.body)?;
Ok(user)
}
}
#[tokio::main]
async fn main() -> Result<()> {
let api = ApiClient::new("gurt://api.example.com".to_string());
// Create a user
let new_user = CreateUser {
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
};
let user = api.create_user(new_user).await?;
println!("Created user: {} (ID: {})", user.name, user.id);
// Retrieve the user
let retrieved_user = api.get_user(user.id).await?;
println!("Retrieved user: {}", retrieved_user.name);
Ok(())
}
```
--------------------------------
### Start GURT Server with Configuration
Source: https://docs.gurted.com/docs/gurty-cli
Starts the GURT server using the 'cargo run' command with the 'serve' subcommand and specifies a configuration file. The '--release' flag indicates a release build for performance.
```bash
cargo run --release serve --config gurty.toml
```
--------------------------------
### Install mkcert on Windows
Source: https://docs.gurted.com/docs/gurt-protocol
Command to install mkcert on Windows using Chocolatey, a package manager.
```bash
# Windows (with Chocolatey)
choco install mkcert
```
--------------------------------
### Build a JSON API Server with Gurted
Source: https://docs.gurted.com/docs/gurt-server
Provides a comprehensive example of building a JSON API server using Gurted. It includes defining a User struct, handling GET and POST requests for user data, and parsing JSON request bodies.
```Rust
use serde::{Deserialize, Serialize};
use serde_json::json;
#[derive(Serialize, Deserialize)]
struct User {
id: u64,
name: String,
email: String,
}
let server = GurtServer::with_tls_certificates("cert.pem", "key.pem")?
.get("/api/users", |ctx| async {
let users = vec![
User { id: 1, name: "Alice".to_string(), email: "alice@example.com".to_string() },
User { id: 2, name: "Bob".to_string(), email: "bob@example.com".to_string() },
];
Ok(GurtResponse::ok()
.with_header("content-type", "application/json")
.with_json_body(&users))
})
.post("/api/users", |ctx| async {
let body = ctx.text()?;
let user: User = serde_json::from_str(&body)
.map_err(|_| GurtError::invalid_message("Invalid JSON"))?;
// Save user to database here...
println!("Creating user: {}", user.name);
Ok(GurtResponse::new(GurtStatusCode::Created)
.with_header("content-type", "application/json")
.with_json_body(&user)?)
})
.get("/api/users/*", |ctx| async {
let path = ctx.path();
if let Some(user_id) = path.strip_prefix("/api/users/") {
if let Ok(id) = user_id.parse::() {
// Get user from database here...
let user = User {
id,
name: format!("User {}", id),
email: format!("user{}@example.com", id),
};
Ok(GurtResponse::ok()
.with_header("content-type", "application/json")
.with_json_body(&user))
} else {
Ok(GurtResponse::bad_request()
.with_string_body("Invalid user ID"))
}
} else {
Ok(GurtResponse::not_found())
}
});
```
--------------------------------
### Create Basic GURT Server
Source: https://docs.gurted.com/docs/gurt-server
Instantiates a new GURT server without any initial configuration, providing a starting point for building server functionalities.
```rust
let server = GurtServer::new();
```
--------------------------------
### Serve with Configuration File
Source: https://docs.gurted.com/docs/gurty-cli
Starts the gurty server using a specified TOML configuration file. This is a common way to manage server settings.
```bash
gurty serve --config gurty.toml
```
--------------------------------
### GURT URL Scheme Examples
Source: https://docs.gurted.com/docs/gurt-protocol
Examples of the 'gurt://' URL scheme used by the GURT protocol. It specifies the format for connecting to GURT servers, including host, port, and path.
```gurt
gurt://example.com/path
```
```gurt
gurt://192.168.1.100:4878/api/data
```
```gurt
gurt://localhost:4878/hello
```
--------------------------------
### Gurty Serve Command Usage
Source: https://docs.gurted.com/docs/gurty-cli
Illustrates the basic usage of the 'gurty serve' command, which starts a GURT server with TLS certificates. It shows the command structure and indicates that options are available.
```bash
gurty serve [OPTIONS]
```
--------------------------------
### Start GURT Server with Explicit Certificates
Source: https://docs.gurted.com/docs/gurty-cli
Starts the GURT server using 'cargo run' and explicitly provides the paths to the TLS certificate and private key files. This is an alternative to specifying them in the configuration file.
```bash
cargo run --release serve --cert localhost+2.pem --key localhost+2-key.pem
```
--------------------------------
### Make a GET Request with GURT Client
Source: https://docs.gurted.com/docs/gurt-client
This example shows how to perform a GET request using the GURT client and check if the request was successful. It prints the response body on success or an error message on failure.
```Rust
let response = client.get("gurt://api.example.com/users").await?;
if response.is_success() {
println!("Success: {}", response.text()?);
} else {
println!("Error: {} {}", response.status_code, response.status_message);
}
```
--------------------------------
### Install mkcert
Source: https://docs.gurted.com/docs/gurt-protocol
Installs a local Certificate Authority (CA) into your system's certificate store, which is necessary for mkcert to generate trusted local certificates.
```bash
mkcert -install
```
--------------------------------
### Generate Development TLS Certificates with mkcert
Source: https://docs.gurted.com/docs/gurt-server
Provides instructions for generating trusted local TLS certificates for development using the `mkcert` tool. It covers installation on Windows and macOS, installing the local CA, and generating certificates for localhost.
```Shell
# Install mkcert
choco install mkcert # Windows
brew install mkcert # macOS
# or download from GitHub releases
# Install local CA
mkcert -install
# Generate certificates
mkcert localhost 127.0.0.1 ::1
```
--------------------------------
### Serve in Debug Mode with Configuration
Source: https://docs.gurted.com/docs/gurty-cli
Starts the gurty server with a configuration file and enables debug logging. This is helpful for troubleshooting server behavior.
```bash
gurty serve --config gurty.toml --log-level debug
```
--------------------------------
### Install mkcert for Development Certificates (Windows)
Source: https://docs.gurted.com/docs/gurty-cli
Installs the mkcert tool on Windows using Chocolatey, a package manager for Windows. mkcert is used to generate local TLS certificates for development environments.
```bash
# Windows (with Chocolatey)
choco install mkcert
```
--------------------------------
### Install mkcert for Development Certificates (macOS)
Source: https://docs.gurted.com/docs/gurty-cli
Installs the mkcert tool on macOS using Homebrew, a package manager for macOS. mkcert is used to generate local TLS certificates for development environments.
```bash
# macOS (with Homebrew)
brew install mkcert
```
--------------------------------
### Deploy GURT Server with Production Certificates
Source: https://docs.gurted.com/docs/gurty-cli
Starts the GURT server using 'cargo run' with production certificates specified via command-line arguments. It also includes the configuration file for server settings.
```bash
cargo run --release serve --cert gurt-server.crt --key gurt-server.key --config gurty.toml
```
--------------------------------
### Install Local CA with mkcert
Source: https://docs.gurted.com/docs/gurty-cli
Installs the mkcert-generated Certificate Authority (CA) into the system's trust store. This allows browsers and other tools to trust the locally generated TLS certificates.
```bash
mkcert -install
```
--------------------------------
### Make a HEAD Request with GURT Client
Source: https://docs.gurted.com/docs/gurt-client
This example demonstrates how to make a HEAD request to retrieve headers for a resource without downloading the body.
```Rust
let response = client.head("gurt://api.example.com/large-file").await?;
// Check headers without downloading body
let content_length = response.headers.get("content-length");
```
--------------------------------
### Border Styling Examples
Source: https://docs.gurted.com/docs/html
Illustrates different border styles supported by Gurted, including variations in width, sides, and colors, using utility classes.
```HTML
Default border (1px)
2px border
4px border
Top border only
Right border only
Bottom border only
Left border only
Solid border
Dashed border
Dotted border
Red border
Custom hex border
```
--------------------------------
### Test Gurt Server and Client in Rust
Source: https://docs.gurted.com/docs/gurt-server
This snippet shows how to create a test for a Gurt server. It includes setting up a server with TLS certificates, defining a route, starting the server in the background, and then using a Gurt client to send a request and assert the response.
```Rust
#[cfg(test)]
mod tests {
use super::*;
use gurt::GurtClient;
#[tokio::test]
async fn test_server() {
let server = GurtServer::with_tls_certificates("test-cert.pem", "test-key.pem")
.unwrap()
.get("/test", |_ctx| async {
Ok(GurtResponse::ok().with_string_body("test response"))
});
// Start server in background
tokio::spawn(async move {
server.listen("127.0.0.1:9999").await.unwrap();
});
// Give server time to start
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
// Test with client
let client = GurtClient::new();
let response = client.get("gurt://127.0.0.1:9999/test").await.unwrap();
assert_eq!(response.status_code, 200);
assert_eq!(response.text().unwrap(), "test response");
}
}
```
--------------------------------
### Flexbox Layout Examples
Source: https://docs.gurted.com/docs/html
Demonstrates various Flexbox configurations using Gurted's utility classes, including row and column layouts, gap, alignment, wrapping, grow/shrink properties, and self-alignment.
```HTML
ABC
Item 1Item 2Item 3
Grow 1Grow 2No Shrink
StartCenterEndStretch
```
--------------------------------
### Generate Localhost Certificates with mkcert
Source: https://docs.gurted.com/docs/gurty-cli
Generates TLS certificates for localhost, 127.0.0.1, and ::1 using mkcert. This creates '.pem' and '-key.pem' files needed for development server setup.
```bash
cd protocol/cli
mkcert localhost 127.0.0.1 ::1
```
--------------------------------
### GURT Protocol Example Session
Source: https://docs.gurted.com/docs/gurt-protocol
Demonstrates a complete GURT communication flow between a client and server, including the initial handshake, protocol confirmation, sending JSON data via POST, and receiving a JSON response.
```plaintext
# Client connects and sends handshake
HANDSHAKE / GURT/1.0.0\r\n
\r\n
# Server confirms protocol
GURT/1.0.0 101 SWITCHING_PROTOCOLS\r\n
\r\n
# All further communication is encrypted
# Client sends JSON data
POST /api/data GURT/1.0.0\r\n
\r\n
{"foo":"bar","x":1}
# Server responds with JSON
GURT/1.0.0 200 OK\r\n
\r\n
{"result":"ok"}
```
--------------------------------
### Install GURT Client via Cargo
Source: https://docs.gurted.com/docs/gurt-client
This snippet shows how to add the GURT client library to your Rust project using Cargo, the Rust package manager.
```Rust
cargo add gurt
```
--------------------------------
### Utility-First CSS Styling in Gurted
Source: https://docs.gurted.com/docs/intro
This example showcases the utility-first CSS approach inspired by Tailwind, implemented natively within the Gurted framework. It demonstrates how to apply styles directly to HTML elements using predefined classes for layout, typography, and color.
```html
Content Area
Style with utility classes
```
--------------------------------
### Border Radius Examples
Source: https://docs.gurted.com/docs/css
Demonstrates various border-radius properties for creating rounded corners on elements. Includes preset sizes and custom pixel/percentage values.
```html
```
--------------------------------
### Make a POST Request with JSON Data using GURT Client
Source: https://docs.gurted.com/docs/gurt-client
This example shows how to send a POST request with JSON data to a GURT server using the `post_json` method.
```Rust
use serde_json::json;
let data = json!({
"name": "John Doe",
"email": "john@example.com"
});
let response = client.post_json("gurt://api.example.com/users", &data).await?;
```
--------------------------------
### HTML Select Dropdown
Source: https://docs.gurted.com/docs/html
Shows how to create an HTML select dropdown menu with options. Includes examples of selected and disabled options, along with basic styling.
```HTML
```
--------------------------------
### GURT Direct IP Access URIs
Source: https://docs.gurted.com/docs/gurt-protocol
Shows examples of GURT URIs for direct IP access, including specifying a host and port, and accessing a specific API endpoint.
```plaintext
gurt://192.168.1.100:4878/
gurt://localhost:4878/api
```
--------------------------------
### Fetch HTTP Requests
Source: https://docs.gurted.com/docs/lua/network
Demonstrates how to make HTTP requests using the fetch function, including simple GET requests and POST requests with custom headers and bodies. It also shows how to check the response status and parse the response data.
```Lua
-- Simple GET request
local response = fetch('https://api.example.com/data')
-- POST request with data
local response = fetch('https://api.example.com/users', {
method = 'POST',
headers = {
['Content-Type'] = 'application/json',
['Authorization'] = 'Bearer token123'
},
body = JSON.stringify({
name = 'John Doe',
email = 'john@example.com'
})
})
-- Check response
if response:ok() then
local data = response:json() -- Parse JSON response
local text = response:text() -- Get as text
trace.log('Status: ' .. response.status)
trace.log('Status Text: ' .. response.statusText)
-- Access headers
local contentType = response.headers['content-type']
else
trace.log('Request failed with status: ' .. response.status)
end
```
--------------------------------
### Configure Server Listening Addresses in Rust
Source: https://docs.gurted.com/docs/gurt-server
Shows how to configure the Gurted server to listen on different network interfaces and ports using the `listen` method. Examples include listening on all interfaces, a specific IPv4 address, and an IPv6 address.
```Rust
// Listen on all interfaces
server.listen("0.0.0.0:4878").await?;
// Listen on specific interface
server.listen("127.0.0.1:8080").await?;
// Listen on IPv6
server.listen("[::1]:4878").await?;
```
--------------------------------
### Define Method-Specific Routes
Source: https://docs.gurted.com/docs/gurt-server
Configures a GURT server with routes for different HTTP methods (GET, POST, PUT, DELETE, PATCH). Each route handler is defined as an asynchronous closure that processes the request and returns a GurtResponse.
```rust
let server = GurtServer::with_tls_certificates("cert.pem", "key.pem")?
.get("/", |_ctx| async {
Ok(GurtResponse::ok().with_string_body("GET request"))
})
.post("/submit", |ctx| async {
let body = ctx.text()?;
println!("Received: {}", body);
Ok(GurtResponse::new(GurtStatusCode::Created).with_string_body("Created"))
})
.put("/update", |_ctx| async {
Ok(GurtResponse::ok().with_string_body("Updated"))
})
.delete("/delete", |_ctx| async {
Ok(GurtResponse::new(GurtStatusCode::NoContent))
})
.patch("/partial", |_ctx| async {
Ok(GurtResponse::ok().with_string_body("Patched"))
});
```
--------------------------------
### Accessing GURT Response Data
Source: https://docs.gurted.com/docs/gurt-client
This example shows how to access various parts of a GURT response, including status information, headers, and the body (as text, bytes, or parsed JSON).
```Rust
let response = client.get("gurt:
```
--------------------------------
### HTML Buttons
Source: https://docs.gurted.com/docs/html
Demonstrates the creation of basic and styled HTML buttons. Includes examples for disabled states, primary and success button styles using inline CSS, and form submission buttons.
```HTML
```
--------------------------------
### HTML Image Display
Source: https://docs.gurted.com/docs/html
Shows how to display images using the HTML img tag. Includes examples for loading images from network URLs and local site paths, with sizing and styling controls.
```HTML
```
--------------------------------
### WebSocket Real-time Communication
Source: https://docs.gurted.com/docs/lua/network
Provides examples for establishing and managing WebSocket connections for real-time communication. It covers connecting to a WebSocket server, sending messages, and handling connection events like open, message, close, and error.
```Lua
local ws = WebSocket.new('ws://localhost:8080/chat')
ws:on('open', function()
trace.log('WebSocket connected')
ws:send('Hello server!')
end)
ws:on('message', function(data)
trace.log('Received: ' .. data)
end)
ws:on('close', function(code, reason)
trace.log('WebSocket closed: ' .. code .. ' - ' .. reason)
end)
ws:on('error', function(error)
trace.log('WebSocket error: ' .. error)
end)
ws:send('Hello from client!')
ws:send(JSON.stringify({ type = 'chat', message = 'Hello!' }))
ws:close()
if ws.readyState == WebSocket.OPEN then
ws:send('Connected message')
end
```
--------------------------------
### Gurted Styled Buttons
Source: https://docs.gurted.com/docs/css
Demonstrates various button styles using Gurted's utility-first CSS, including different colors, shapes, and interactive states like hover and active effects. These examples highlight the flexibility in styling buttons.
```html
```
--------------------------------
### Control Audio Playback with Gurt
Source: https://docs.gurted.com/docs/lua/audio
This snippet demonstrates how to select an audio element using Gurt and control its playback. It covers starting, pausing, and stopping audio, as well as seeking to specific times, adjusting volume, enabling looping, and changing the audio source. It also shows how to retrieve properties like duration, current time, and playback status.
```lua
local audio = gurt.select('#my-audio')
audio:play() -- Start playback
audio:pause() -- Pause playback
audio:stop() -- Stop and reset
audio.currentTime = 30.0 -- Seek to 30 seconds
audio.volume = 0.8 -- Set volume (0.0 - 1.0)
audio.loop = true -- Enable looping
audio.src = 'gurt://new-audio.mp3' -- Change source
local duration = audio.duration
local currentPos = audio.currentTime
local isPlaying = audio.playing
local isPaused = audio.paused
```
--------------------------------
### Create GURT Server with TLS
Source: https://docs.gurted.com/docs/gurt-server
Demonstrates two ways to configure a GURT server with TLS certificates: either during initial creation or by loading them after the server has been instantiated.
```rust
// Load TLS certificates during server creation
let server = GurtServer::with_tls_certificates("cert.pem", "key.pem")?;
// Or load certificates later
let mut server = GurtServer::new();
server.load_tls_certificates("cert.pem", "key.pem")?;
```
--------------------------------
### Create a Default GURT Client
Source: https://docs.gurted.com/docs/gurt-client
This code demonstrates how to create a new instance of the GURT client with default configurations.
```Rust
let client = GurtClient::new();
```
--------------------------------
### Deploy GURT Server with Production Certificates
Source: https://docs.gurted.com/docs/gurt-protocol
Command to run a GURT server in release mode, specifying the certificate and key files, host, and port.
```rust
cargo run --release serve --cert gurt-server.crt --key gurt-server.key --host 0.0.0.0 --port 4878
```
--------------------------------
### Get Canvas Contexts
Source: https://docs.gurted.com/docs/lua/canvas
Selects a canvas element by its ID and retrieves both the 2D drawing context and a shader context for rendering.
```lua
local canvas = gurt.select('#my-canvas')
local ctx = canvas:withContext('2d')
local shaderCtx = canvas:withContext('shader')
```
--------------------------------
### Create Basic HTTP Responses
Source: https://docs.gurted.com/docs/gurt-server
Demonstrates how to create various HTTP responses using GurtResponse, including success, client error, and server error status codes.
```Rust
// Success responses
GurtResponse::ok() // 200 OK
GurtResponse::new(GurtStatusCode::Created) // 201 Created
GurtResponse::new(GurtStatusCode::Accepted) // 202 Accepted
GurtResponse::new(GurtStatusCode::NoContent) // 204 No Content
// Client error responses
GurtResponse::bad_request() // 400 Bad Request
GurtResponse::new(GurtStatusCode::Unauthorized) // 401 Unauthorized
GurtResponse::new(GurtStatusCode::Forbidden) // 403 Forbidden
GurtResponse::not_found() // 404 Not Found
GurtResponse::new(GurtStatusCode::MethodNotAllowed) // 405 Method Not Allowed
// Server error responses
GurtResponse::internal_server_error() // 500 Internal Server Error
GurtResponse::new(GurtStatusCode::NotImplemented) // 501 Not Implemented
GurtResponse::new(GurtStatusCode::ServiceUnavailable) // 503 Service Unavailable
```
--------------------------------
### Navigate and Copy Configuration Template
Source: https://docs.gurted.com/docs/gurty-cli
This command navigates to the CLI directory and copies the template TOML configuration file to a new file named 'gurty.toml'. This is a common first step for customizing server settings.
```bash
cd protocol/cli
cp gurty.template.toml gurty.toml
```
--------------------------------
### Gurted Radio Button Input
Source: https://docs.gurted.com/docs/html
Shows the radio button input type in Gurted, used for selecting one option from a group, with an example of a pre-selected option.
```Gurted
PizzaPastaSalad
```
--------------------------------
### Define Routes with Path Patterns
Source: https://docs.gurted.com/docs/gurt-server
Illustrates how to define routes using path patterns, including exact matches and wildcard matching with '*'. This allows for flexible routing based on URL structure.
```rust
let server = server
.get("/users", |_ctx| async {
Ok(GurtResponse::ok().with_string_body("All users"))
})
.get("/users/*", |ctx| async {
// Matches /users/123, /users/profile, etc.
let path = ctx.path();
Ok(GurtResponse::ok().with_string_body(format!("User path: {}", path)))
})
.get("/api/*", |_ctx| async {
// Matches any path starting with /api/
Ok(GurtResponse::ok().with_string_body("API endpoint"))
});
```
--------------------------------
### Access Adjacent Sibling Elements
Source: https://docs.gurted.com/docs/lua/elements
Explains how to get the next and previous sibling elements of a given element using `nextSibling` and `previousSibling` properties. This facilitates horizontal traversal of the DOM.
```lua
local current = gurt.select('#current-item')
local next = current.nextSibling
local prev = current.previousSibling
```
--------------------------------
### Get/Set Element Text Content
Source: https://docs.gurted.com/docs/lua/elements
Demonstrates how to get or set the text content of a Gurt element using the `text` property. This is useful for updating displayed text or retrieving it for processing.
```lua
local p = gurt.select('p')
p.text = 'New paragraph content'
local currentText = p.text
```
--------------------------------
### HTML Interactive States
Source: https://docs.gurted.com/docs/html
Illustrates styling elements based on interactive states like hover and active using pseudo-classes. Includes examples for buttons and clickable divs with cursor styling.
```HTML
Clickable container with pointer cursor
Child elements inherit the cursor style
```
--------------------------------
### Create HTTP Responses with Custom Headers
Source: https://docs.gurted.com/docs/gurt-server
Illustrates how to add custom headers to an HTTP response, along with a string body. Demonstrates setting multiple headers, including content type and cache control.
```Rust
GurtResponse::ok()
.with_string_body("Custom response")
.with_header("x-custom-header", "custom-value")
.with_header("cache-control", "no-cache")
.with_header("content-type", "text/plain; charset=utf-8")
```
--------------------------------
### Create Non-Blocking Delay with Time.delay
Source: https://docs.gurted.com/docs/lua/intro
Creates a non-blocking delay object that can be used to pause execution for a specified number of seconds. You can check if the delay is complete or get the remaining time.
```lua
local delay = Time.delay(3.0)
-- Check if delay is complete
if delay:complete() then
trace.log('Delay finished!')
end
-- Get remaining time
local remaining = delay:remaining()
trace.log('Time left: ' .. remaining .. ' seconds')
```
--------------------------------
### Implement Middleware with Rust
Source: https://docs.gurted.com/docs/gurt-server
Demonstrates the middleware pattern in Rust for request logging and authentication. It shows how to define middleware functions and apply them to specific routes.
```Rust
// Request logging middleware
async fn log_request(ctx: &ServerContext) -> Result<()> {
println!("{} {} from ",
ctx.method(),
ctx.path(),
ctx.client_ip()
);
Ok(())
}
// Authentication middleware
async fn require_auth(ctx: &ServerContext) -> Result<()> {
if let Some(auth_header) = ctx.header("authorization") {
if auth_header.starts_with("Bearer ") {
// Validate token here...
return Ok(());
}
}
Err(GurtError::invalid_message("Authentication required"))
}
let server = server
.get("/protected", |ctx| async {
// Apply middleware
log_request(ctx).await?;
require_auth(ctx).await?;
Ok(GurtResponse::ok()
.with_string_body("Protected content"))
})
.post("/api/data", |ctx| async {
log_request(ctx).await?;
// Handle request
Ok(GurtResponse::ok()
.with_string_body("Data processed"))
});
```
--------------------------------
### Serve Files with Rust
Source: https://docs.gurted.com/docs/gurt-server
Implements a file server using Rust and Tokio. It handles requests for static files, prevents directory traversal attacks, determines content types based on file extensions, and returns file content or a not found error.
```Rust
use std::path::Path;
use tokio::fs;
let server = server.get("/files/*", |ctx| async {
let path = ctx.path();
let file_path = path.strip_prefix("/files/").unwrap_or("");
// Security: prevent directory traversal
if file_path.contains("..") {
return Ok(GurtResponse::new(GurtStatusCode::Forbidden)
.with_string_body("Access denied"));
}
let full_path = format!("./static/{}", file_path);
match fs::read(&full_path).await {
Ok(data) => {
let content_type = match Path::new(&full_path).extension()
.and_then(|ext| ext.to_str()) {
Some("html") => "text/html",
Some("css") => "text/css",
Some("js") => "application/javascript",
Some("json") => "application/json",
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("gif") => "image/gif",
_ => "application/octet-stream",
};
Ok(GurtResponse::ok()
.with_header("content-type", content_type)
.with_body(data))
}
Err(_) => {
Ok(GurtResponse::not_found()
.with_string_body("File not found"))
}
}
});
```
--------------------------------
### Create HTTP Responses with String, JSON, or Binary Body
Source: https://docs.gurted.com/docs/gurt-server
Shows how to attach different types of bodies to HTTP responses: plain strings, JSON objects, and binary data like images. Includes setting the content type header for binary data.
```Rust
// String body
GurtResponse::ok().with_string_body("Hello, World!")
// JSON body
use serde_json::json;
let data = json!({"message": "Hello", "status": "success"});
GurtResponse::ok().with_json_body(&data)
// Binary body
let image_data = std::fs::read("image.png")?;
GurtResponse::ok()
.with_header("content-type", "image/png")
.with_body(image_data)
```
--------------------------------
### Make an OPTIONS Request with GURT Client
Source: https://docs.gurted.com/docs/gurt-client
This code shows how to make an OPTIONS request to a GURT server endpoint to determine the allowed HTTP methods.
```Rust
let response = client.options("gurt://api.example.com/endpoint").await?;
// Check allowed methods
let allowed_methods = response.headers.get("allow");
```
--------------------------------
### URL Decoding
Source: https://docs.gurted.com/docs/lua/network
Illustrates the usage of the urlDecode function to convert percent-encoded URL strings back into their original, human-readable format. Examples show decoding simple strings and query parameters.
```Lua
local decoded = urlDecode('hello%20world%21')
trace.log(decoded) -- hello world!
local params = urlDecode('name%3DJohn%20Doe%26age%3D30')
trace.log(params) -- name=John Doe&age=30
local queryParam = 'cats%20%26%20dogs'
local searchTerm = urlDecode(queryParam)
trace.log(searchTerm) -- cats & dogs
```
--------------------------------
### Gurted Links
Source: https://docs.gurted.com/docs/html
Demonstrates creating links in Gurted, supporting both external URLs and internal GURT protocol links.
```Gurted
External linkGURT protocol link
```
--------------------------------
### Get/Set Form Element Values
Source: https://docs.gurted.com/docs/lua/elements
Explains how to get and set the values of form elements like input fields and checkboxes using the `value` property. This is essential for handling user input and form state.
```lua
local input = gurt.select('#username')
input.value = 'john_doe'
local username = input.value
local checkbox = gurt.select('#agree')
checkbox.value = true -- Check the checkbox
```
--------------------------------
### Create a GURT Client with Custom Configuration
Source: https://docs.gurted.com/docs/gurt-client
This snippet shows how to create a GURT client with custom settings, including connection timeouts, request timeouts, handshake timeouts, user agent, and maximum redirects.
```Rust
use tokio::time::Duration;
let config = GurtClientConfig {
connect_timeout: Duration::from_secs(10),
request_timeout: Duration::from_secs(30),
handshake_timeout: Duration::from_secs(5),
user_agent: "MyApp/1.0.0".to_string(),
max_redirects: 5,
};
let client = GurtClient::with_config(config);
```
--------------------------------
### HTML Margin Utilities
Source: https://docs.gurted.com/docs/css
Illustrates Flumi's margin utility classes for creating space outside elements. Examples include margin on all sides and specific vertical margins, along with custom pixel values.
```HTML
Margin all sides (16px) - Space around the red area
Top 24px, bottom 16px margin - Vertical spacing only
Custom 20px padding, 10px margin
```
--------------------------------
### Generate Production TLS Certificates with OpenSSL
Source: https://docs.gurted.com/docs/gurt-server
Details the process of generating production-ready TLS certificates using OpenSSL. It includes commands for creating a private key, a certificate signing request (CSR), and a self-signed certificate, as well as a one-step command for generating both key and certificate.
```Shell
# Generate private key
openssl genpkey -algorithm RSA -out server.key -pkcs8
# Generate certificate signing request
openssl req -new -key server.key -out server.csr
# Generate self-signed certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
# Or in one step
openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365 -nodes
```