### startServer() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-control.md Starts the server instance. This is typically handled automatically by the system. ```APIDOC ## startServer() ### Description Starts the server. This method is usually called automatically by braceEnd and is typically not needed for manual invocation. ### Signature `startServer()` ``` -------------------------------- ### Start the server Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-control.md Initiates the server process. This is typically handled automatically by braceEnd. ```ring startServer() # Usually not needed ``` -------------------------------- ### Usage examples for the icon shortcode Source: https://github.com/ysdragon/bolt/blob/master/docs/site/layouts/_shortcodes/icon.html Demonstrates how to invoke the icon shortcode using either named or positional parameters. ```html {{< icon name="github" >}} ``` ```html {{< icon "github" >}} ``` -------------------------------- ### MiniJinja template syntax example Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/templates.md Demonstrates standard MiniJinja syntax including variable interpolation, loops, and conditional logic. ```html
Welcome, {{ user }}!
{% endif %} ``` -------------------------------- ### Usage examples for the term shortcode Source: https://github.com/ysdragon/bolt/blob/master/docs/site/layouts/_shortcodes/term.html Demonstrates the two ways to invoke the term shortcode using either a named parameter or a positional parameter. ```hugo {{< term entry="MAC" >}} ``` ```hugo {{< term "MAC" >}} ``` -------------------------------- ### Install Bolt via Ring Package Manager Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/installation.md Use the Ring Package Manager to install the Bolt package from the ysdragon repository. ```bash ringpm install bolt from ysdragon ``` -------------------------------- ### Verify Server Output Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/installation.md Expected console output when the Bolt server starts successfully. ```text [bolt] Server running on http://0.0.0.0:3000 ``` -------------------------------- ### @get(cPath, fHandler) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/routing.md Registers a GET route to handle incoming GET requests at the specified path. ```APIDOC ## @get(cPath, fHandler) ### Description Registers a GET route. ### Parameters - **cPath** (string) - Required - The URL path to match. - **fHandler** (function) - Required - The handler function to execute. ``` -------------------------------- ### Register a GET route Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/routing.md Uses the @get decorator to define a route for GET requests. ```ring @get("/users", func { $bolt.json([:users = []]) }) ``` -------------------------------- ### Set Custom Headers in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/response-methods.md Example of setting custom HTTP headers before sending a file response. ```ring @get("/download", func { $bolt.setHeader("Content-Disposition", "attachment; filename=data.csv") $bolt.setHeader("Cache-Control", "no-cache") $bolt.sendFile("./exports/data.csv") }) ``` -------------------------------- ### Get environment variable with default Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Retrieve an environment variable or provide a fallback value if the key is missing. ```ring port = env.getVar("PORT") if port = "" port = "3000" ok # Or more concisely: port = env.getOr("PORT", "3000") ``` -------------------------------- ### Implement Before and After Hooks in Bolt Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/middleware.md Use @before and @after decorators to execute logic globally before or after request processing. This example demonstrates request logging, header manipulation, and authentication checks. ```ring new Bolt() { port = 3000 # Runs BEFORE every request @before(func { # Add request ID header $bolt.setHeader("X-Request-Id", $bolt.requestId()) # Log request $bolt.log("[" + $bolt.method() + "] " + $bolt.path()) # Authentication check auth = $bolt.header("Authorization") if $bolt.path() != "/login" and $bolt.path() != "/public" and auth = "" $bolt.unauthorized() return ok }) # Runs AFTER every request @after(func { # Add timing header $bolt.setHeader("X-Response-Time", "" + $bolt.unixtimeMs()) # Log completion $bolt.log("Request completed: " + $bolt.path()) }) @get("/", func { $bolt.send("Home") }) @get("/login", func { $bolt.send("Login page") }) @get("/dashboard", func { $bolt.send("Dashboard (protected)") }) } ``` -------------------------------- ### Define HTTP Method Handlers in Bolt Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/routing-basics.md Demonstrates how to map standard HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) to specific handler functions within a Bolt application. ```ring new Bolt() { port = 3000 # GET - Retrieve data @get("/users", func { $bolt.json([:users = [[:id = 1, :name = "Alice"]]]) }) # POST - Create data @post("/users", func { data = $bolt.jsonBody() $bolt.jsonWithStatus(201, [:created = true, :user = data]) }) # PUT - Update/replace data @put("/users/:id", func { data = $bolt.jsonBody() $bolt.json([:updated = $bolt.param("id"), :data = data]) }) # PATCH - Partial update @patch("/users/:id", func { data = $bolt.jsonBody() $bolt.json([:patched = $bolt.param("id")]) }) # DELETE - Remove data @delete("/users/:id", func { $bolt.sendStatus(204) # No content }) # HEAD - Headers only (no body) @head("/health", func { $bolt.setHeader("X-Status", "healthy") $bolt.sendStatus(200) }) # OPTIONS - CORS preflight @options("/api/*", func { $bolt.setHeader("Allow", "GET, POST, PUT, DELETE, OPTIONS") $bolt.sendStatus(200) }) } ``` -------------------------------- ### Test API endpoints with curl Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/testing-deployment.md Use these commands to verify API functionality including GET, POST, authentication, and file uploads. ```bash # GET request curl http://localhost:3000/users # POST JSON curl -X POST http://localhost:3000/users \ -H "Content-Type: application/json" \ -d '{"name":"John","email":"john@example.com"}' # With authentication curl http://localhost:3000/profile \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." # File upload curl -X POST http://localhost:3000/upload \ -F "file=@photo.jpg" ``` -------------------------------- ### Define HTTP Method Endpoints in Bolt Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/basic-routing.md Use standard HTTP verbs like GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS to define route handlers. Requires loading bolt.ring and initializing a Bolt instance. ```ring load "bolt.ring" new Bolt() { port = 3000 # GET - Retrieve data @get("/users", func { $bolt.json([:users = [[:id = 1, :name = "Alice"]]]) }) # POST - Create data @post("/users", func { data = $bolt.jsonBody() $bolt.jsonWithStatus(201, [:created = true, :user = data]) }) # PUT - Update/replace data @put("/users/:id", func { data = $bolt.jsonBody() $bolt.json([:updated = $bolt.param("id"), :data = data]) }) # PATCH - Partial update @patch("/users/:id", func { data = $bolt.jsonBody() $bolt.json([:patched = $bolt.param("id")]) }) # DELETE - Remove data @delete("/users/:id", func { $bolt.sendStatus(204) # No content }) # HEAD - Headers only (no body) @head("/health", func { $bolt.setHeader("X-Status", "healthy") $bolt.sendStatus(200) }) # OPTIONS - CORS preflight @options("/api/*", func { $bolt.setHeader("Allow", "GET, POST, PUT, DELETE, OPTIONS") $bolt.sendStatus(200) }) } ``` -------------------------------- ### Get environment variable Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Retrieve the value of an environment variable, returning an empty string if it does not exist. ```ring dbUrl = env.getVar("DATABASE_URL") ``` -------------------------------- ### Create a Hello World Bolt application Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/your-first-app.md Initializes a basic Bolt server and sends a text response. ```ring load "bolt.ring" new Bolt() { $bolt.send("Hello, World!") } ``` -------------------------------- ### Get a cookie value Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/cookies.md Retrieves the value of a cookie by its name. ```ring user = $bolt.cookie("user") ``` -------------------------------- ### Get Request Header Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves the value of a specific request header. ```ring auth = $bolt.header("Authorization") contentType = $bolt.header("Content-Type") ``` -------------------------------- ### Get URL Parameter Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves a specific URL parameter by name. ```ring # Route: /users/:id id = $bolt.param("id") ``` -------------------------------- ### Initialize Env class Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Create a new instance of the Env class. ```ring env = new Env() ``` -------------------------------- ### Get HTTP Method Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves the HTTP method of the current request. ```ring m = $bolt.method() # "GET", "POST", etc. ``` -------------------------------- ### Enable default homepage with API documentation links Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/openapi-documentation.md Adds a root endpoint that displays server information and links to the generated API documentation. ```ring new Bolt() { port = 3000 setDocsInfo("My API", "1.0.0", "My awesome API") enableDocs() homepage() # Adds "/" with server info (skips if "/" already defined) # Your routes... } ``` -------------------------------- ### Create a complete Bolt application with routing Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/your-first-app.md Demonstrates routing, URL parameters, JSON responses, and request body parsing. ```ring load "bolt.ring" new Bolt() { port = 3000 @get("/", func { $bolt.send("Hello from Bolt!") }) @get("/users/:id", func { $bolt.json([ :id = $bolt.param("id"), :name = "User " + $bolt.param("id") ]) }) where("id", "[0-9]+") @post("/users", func { data = $bolt.jsonBody() $bolt.jsonWithStatus(201, [:created = true, :data = data]) }) } ``` -------------------------------- ### Get flash message in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/sessions.md Retrieves and immediately clears a flash message. ```ring msg = $bolt.getFlash("success") ``` -------------------------------- ### Full Bolt Application Configuration Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/complete-example.md Initializes a Bolt server with custom limits, CORS, logging, and OpenAPI documentation, followed by route definitions and static file serving. ```ring load "bolt.ring" new Bolt() { port = 3000 # Configuration setBodyLimit(10 * 1024 * 1024) setTimeout(30000) enableCors() corsOrigin("*") enableCompression() enableLogging() # OpenAPI docs setDocsInfo("User API", "1.0.0", "User management API") enableDocs() # Middleware @before(func { $bolt.setHeader("X-Request-Id", $bolt.requestId()) }) # Routes prefix("/api/v1") @get("/users", func { $bolt.json([:users = []]) }) describe("Get all users") tag("Users") @get("/users/:id", func { $bolt.json([:id = $bolt.param("id")]) }) where("id", "[0-9]+") describe("Get user by ID") tag("Users") @post("/users", func { data = $bolt.jsonBody() $bolt.jsonWithStatus(201, [:created = true, :data = data]) }) describe("Create new user") tag("Users") endPrefix() # Static files @static("/public", "./static") # Health check @get("/health", func { $bolt.json([:status = "ok", :time = $bolt.unixtime()]) }) } ``` -------------------------------- ### Get Request Body Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves the request body as a string or base64-encoded string. ```ring raw = $bolt.body() ``` ```ring encoded = $bolt.bodyBase64() ``` -------------------------------- ### Configure OpenAPI documentation in Bolt Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/openapi-documentation.md Initializes the Bolt server with API metadata and route descriptions for Swagger UI generation. ```ring new Bolt() { port = 3000 # Set API info setDocsInfo("User API", "2.0.0", "API for managing users") # Enable Swagger UI at /docs enableDocs() # Document routes @get("/users", func { $bolt.json([:users = []]) }) describe("List all users") tag("Users") @get("/users/:id", func { $bolt.json([:id = $bolt.param("id")]) }) where("id", "[0-9]+") describe("Get user by ID") tag("Users") @post("/users", func { data = $bolt.jsonBody() $bolt.jsonWithStatus(201, [:id = 1]) }) describe("Create new user") tag("Users") } ``` -------------------------------- ### Get Request Path Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves the route pattern associated with the request path. ```ring p = $bolt.path() # "/users/:id" (route pattern, not actual URI) ``` -------------------------------- ### Create a Bolt Application Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/installation.md Define a basic Bolt server instance listening on port 3000 with a root route handler. ```ring load "bolt.ring" new Bolt() { port = 3000 @get("/", func { $bolt.send("Hello, World!") }) } ``` -------------------------------- ### Get current Unix timestamp Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/datetime-class.md Retrieve the current Unix timestamp in seconds. ```ring ts = dt.timestamp() ``` -------------------------------- ### Enable Swagger UI Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/openapi-documentation.md Activates the Swagger UI interface at the /docs endpoint. ```ring enableDocs() ``` -------------------------------- ### Get session value in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/sessions.md Retrieves the value associated with a specific session key. ```ring userId = $bolt.getSession("user_id") ``` -------------------------------- ### Env Class Initialization Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Instantiate the Env class to begin managing environment variables. ```APIDOC ## Env() ### Description Creates a new instance of the Env class. ### Usage ```ring env = new Env() ``` ``` -------------------------------- ### Icon shortcode implementation Source: https://github.com/ysdragon/bolt/blob/master/docs/site/layouts/_shortcodes/icon.html The logic for retrieving and rendering an icon based on the provided name and attributes. ```go-html-template {{- /* Create an icon. @param {string} name The name of the icon. @param {string} attributes The attributes of the icon. or @param {string} 0 The name of the icon. @example {{< icon name="github" >}} @example {{< icon "github" >}} */ -}} {{- $name := .Get "name" | default (.Get 0) -}} {{- $icon := index hugo.Data.icons $name -}} {{- $attributes := .Get "attributes" | default "height=1em"}} {{- if not $icon -}} {{ errorf "icon %q not found" $name }} {{- end -}} {{- $icon = replaceRE " {{- $icon | safeHTML -}} ``` -------------------------------- ### Get Form Fields Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves form field values from multipart form data. ```ring username = $bolt.formField("username") password = $bolt.formField("password") ``` ```ring # # hobbies = $bolt.formFieldAll("hobby") # ["reading", "coding"] ``` -------------------------------- ### Toggle Logging Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-configuration.md Enable request logging for the server. ```ring enableLogging() ``` -------------------------------- ### Get Request URI Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves the raw request URI including the query string. ```ring u = $bolt.uri() # "/users/123?tab=profile" ``` -------------------------------- ### Load .env file Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Load the .env file from the current directory. ```ring env.loadEnv() ``` -------------------------------- ### Get current Unix timestamp in milliseconds Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/datetime-class.md Retrieve the current Unix timestamp in milliseconds. ```ring tsMs = dt.timestampMs() ``` -------------------------------- ### Manage Environment Variables with Env Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/utility-classes.md Use the Env class to load .env files and retrieve configuration variables. ```ring env = new Env() # Automatically loads .env from current directory on init dbUrl = env.getVar("DATABASE_URL") port = env.getVar("PORT") secret = env.getOr("SECRET", "default-secret") # Load from a specific file env.loadFile("/etc/myapp/env") # Set a variable env.setVar("APP_ENV", "production") ``` ```text DATABASE_URL=postgres://localhost/mydb SECRET=my-secret-key PORT=3000 ``` -------------------------------- ### Initialize Crypto class Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/crypto-class.md Instantiate the Crypto object to access encryption and signing methods. ```ring crypto = new Crypto ``` -------------------------------- ### Initialize Syntax Highlighting on Load Source: https://github.com/ysdragon/bolt/blob/master/examples/advanced/templates/layout.html Applies the highlightBash function to all code blocks once the DOM is ready. ```javascript document.addEventListener('DOMContentLoaded', function () { var blocks = document.querySelectorAll('.code-block pre'); for (var i = 0; i < blocks.length; i++) { var raw = blocks[i].textContent; blocks[i].innerHTML = highlightBash(raw); } }); ``` -------------------------------- ### Get current UTC datetime Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/datetime-class.md Retrieve the current UTC datetime string in ISO format. ```ring cUtc = dt.nowUtc() ``` -------------------------------- ### Get current local datetime Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/datetime-class.md Retrieve the current local datetime string in ISO format. ```ring cNow = dt.now() # "2026-05-02T14:30:00" ``` -------------------------------- ### Configure Bolt Server Settings Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/configuration.md Initializes the Bolt server with network, performance, security, and documentation settings. ```ring load "bolt.ring" new Bolt() { # Server port = 3000 host = "0.0.0.0" # Timeouts & Limits setTimeout(30000) # 30 second timeout setBodyLimit(50 * 1024 * 1024) # 50MB max body setSessionCapacity(100000) # 100k sessions setSessionTTL(3600) # 1 hour session TTL setCacheCapacity(50000) # 50k cache entries setCacheTTL(600) # 10 minute cache TTL # Security enableCors() corsOrigin("https://myapp.com") corsOrigin("https://admin.myapp.com") ipWhitelist("10.0.0.0/8") ipBlacklist("1.2.3.4") $bolt.rateLimit(1000, 60) # 1000 req/min enableCsrf("my-csrf-secret") setCookieSecret("my-cookie-secret-key-32chars!") # Features enableCompression() enableLogging() # TLS (production) # enableTls("cert.pem", "key.pem") # Documentation setDocsInfo("My API", "1.0.0", "Production API") enableDocs() # Routes... } ``` -------------------------------- ### Configure Bolt Server Source: https://github.com/ysdragon/bolt/blob/master/README.md Initialize a new Bolt instance with custom port, host, limits, and security features. ```ring new Bolt() { port = 3000 host = "0.0.0.0" # Limits setBodyLimit(50 * 1024 * 1024) setTimeout(30000) setSessionCapacity(10000) setSessionTTL(300) setCacheCapacity(50000) setCacheTTL(600) # Security & features enableCors() enableCompression() enableLogging() enableDocs() homepage() # Routes... } ``` -------------------------------- ### Get Unix timestamps with $bolt.unixtime() and $bolt.unixtimeMs() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/utilities.md Retrieves the current Unix timestamp in either seconds or milliseconds. ```ring ts = $bolt.unixtime() # 1706889600 ``` ```ring ts = $bolt.unixtimeMs() # 1706889600123 ``` -------------------------------- ### Render template file as response Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/templates.md Use this method to render a template file from the filesystem and send it as the HTTP response. ```ring @get("/", func { $bolt.renderFile("templates/home.html", [:user = "John"]) }) ``` -------------------------------- ### Get Request Metadata Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves request-specific metadata like the unique ID or client IP address. ```ring id = $bolt.requestId() # "550e8400-e29b-41d4-a716-446655440000" ``` ```ring ip = $bolt.clientIp() # "192.168.1.100" ``` -------------------------------- ### Get Query Parameters Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves query string parameters, either as a single value or a list of all values. ```ring # URL: /search?q=hello&page=1 q = $bolt.query("q") # "hello" page = $bolt.query("page") # "1" ``` ```ring # URL: /search?tag=rust&tag=web tags = $bolt.queryAll("tag") # ["rust", "web"] ``` -------------------------------- ### Define project directory structure Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/static-files.md Organize static assets within a dedicated directory to ensure they are accessible via the configured routes. ```text project/ ├── app.ring └── static/ ├── css/ │ └── style.css ├── js/ │ └── app.js └── images/ └── logo.png ``` -------------------------------- ### Perform health check with Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/health.md Registers a GET route at /health that returns the result of the health check. ```ring @get("/health", func { $bolt.send($bolt.healthCheck()) }) ``` -------------------------------- ### Serve static directories with @static Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/static-files.md Use the @static directive to map a URL path to a local directory. Multiple directories can be mapped independently. ```ring # Serve ./static directory at /public URL @static("/public", "./static") # Multiple directories @static("/css", "./assets/css") @static("/js", "./assets/js") @static("/images", "./assets/images") ``` -------------------------------- ### Toggle Compression Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-configuration.md Enable response compression for the server. ```ring enableCompression() ``` -------------------------------- ### Initialize DateTime instance Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/datetime-class.md Create a new instance of the DateTime class. ```ring dt = new DateTime ``` -------------------------------- ### Get and verify a signed cookie Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/cookies.md Retrieves and validates a signed cookie. Returns an empty string if the signature is invalid. ```ring data = $bolt.getSignedCookie("session") ``` -------------------------------- ### List all uploaded files with $bolt.files() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/file-uploads.md Retrieves all uploaded files as a list of file lists for iteration. ```ring aFiles = $bolt.files() for f in aFiles ? f[:name] next ``` -------------------------------- ### homepage() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/openapi-documentation.md Adds a default homepage to the server. ```APIDOC ## homepage() ### Description Adds a default homepage at / displaying server info and registered routes. This route is only added if / is not already defined. ### Usage ```ring homepage() ``` ``` -------------------------------- ### Basic WebSocket Server in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/websocket.md Initializes a Bolt server with a basic HTML client and event-driven WebSocket callbacks. ```ring load "bolt.ring" new Bolt() { port = 3000 # Serve HTML client @get("/", func { html = ' ' $bolt.send(html) }) # WebSocket endpoint with event-driven callbacks @ws("/ws", func { id = $bolt.wsClientId() $bolt.wsSendTo(id, "Welcome!") }, func { $bolt.wsBroadcast("[User] " + $bolt.wsEventMessage()) }, func { } ) } ``` -------------------------------- ### Initialize Hash Class Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/hash-class.md Create a new instance of the Hash class to access hashing methods. ```ring hash = new Hash ``` -------------------------------- ### Measure Request Execution Time Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/middleware.md Calculate request duration by storing a start timestamp in the session during the @before hook and calculating the delta in the @after hook. ```ring @before(func { $bolt.setSession("_start_time", "" + $bolt.unixtimeMs()) }) @after(func { startTime = number($bolt.getSession("_start_time")) duration = $bolt.unixtimeMs() - startTime $bolt.setHeader("X-Response-Time", "" + duration + "ms") }) ``` -------------------------------- ### Implement SSE Server with Bolt Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/server-sent-events.md Sets up a Bolt server with an SSE endpoint, a client-side listener, and broadcast triggers for messages and named events. ```ring load "bolt.ring" new Bolt() { port = 3000 # Client page @get("/", func { html = ' ' $bolt.send(html) }) # SSE endpoint - clients connect here @sse("/events") # Trigger endpoint - send events from here @post("/notify", func { message = $bolt.jsonBody()[:message] # Send to all connected clients $bolt.sseBroadcast("/events", message) $bolt.json([:sent = true]) }) # Named events @post("/alert", func { data = $bolt.jsonBody() $bolt.sseBroadcastEvent("/events", "notification", data[:text]) $bolt.json([:sent = true]) }) } ``` -------------------------------- ### Enable TLS in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/testing-deployment.md Configure TLS by providing paths to the certificate and key files. ```ring enableTls("cert.pem", "key.pem") ``` -------------------------------- ### Serve static files Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/routing.md Uses the @static decorator to map a URL path to a local directory. ```ring @static("/public", "./static") @static("/assets", "/var/www/assets") ``` -------------------------------- ### Handle file upload route Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/file-uploads.md Demonstrates a complete workflow for checking, iterating, and saving multiple uploaded files within a POST route. ```ring @post("/upload", func { if $bolt.filesCount() > 0 for i = 1 to $bolt.filesCount() f = $bolt.file(i) $bolt.fileSave(i, "./uploads/" + f[:name]) next $bolt.json([:uploaded = $bolt.filesCount()]) else $bolt.badRequest("No files uploaded") ok }) ``` -------------------------------- ### Configure HTTPS and TLS Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/security.md Enable TLS for secure connections and force HTTPS redirects. ```ring new Bolt() { port = 443 # Enable TLS enableTls("./certs/server.crt", "./certs/server.key") # Force HTTPS redirect @before(func { if $bolt.header("X-Forwarded-Proto") = "http" $bolt.redirectPermanent("https://" + $bolt.header("Host") + $bolt.path()) ok }) # Routes... } ``` -------------------------------- ### enableTls(cCertPath, cKeyPath) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-configuration.md Enables HTTPS with TLS certificates. ```APIDOC ## enableTls(cCertPath, cKeyPath) ### Description Enables HTTPS using the provided TLS certificate and key files. ### Parameters - **cCertPath** (string) - Required - Path to the certificate file. - **cKeyPath** (string) - Required - Path to the private key file. ``` -------------------------------- ### POST /login Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md Demonstrates processing form data, managing sessions, and handling redirects or errors. ```APIDOC ## POST /login ### Description Processes form fields for authentication, sets a session variable, and redirects the user or returns a bad request error. ### Method POST ### Endpoint /login ``` -------------------------------- ### Add Default Homepage Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/openapi-documentation.md Registers a default homepage at the root path displaying server information and routes, provided the route is not already defined. ```ring homepage() ``` -------------------------------- ### Apply multiple route constraints Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/route-modifiers.md Use whereAll to define multiple parameter constraints simultaneously using an array. ```ring @get("/posts/:year/:month", func { ... }) whereAll([ ["year", "[0-9]{4}"], ["month", "[0-9]{2}"] ]) ``` -------------------------------- ### Load specific environment file Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Load environment variables from a custom file path. ```ring env.loadFile("/etc/myapp/env") ``` -------------------------------- ### Initialize Sanitize class Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/sanitize-class.md Create a new instance of the Sanitize class. ```ring s = new Sanitize ``` -------------------------------- ### Configure systemd service Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/testing-deployment.md Define a systemd unit file to manage the application process in production. ```ini [Unit] Description=Bolt API Server After=network.target [Service] Type=simple User=www-data WorkingDirectory=/var/www/myapp ExecStart=/usr/bin/ring app.ring Restart=always [Install] WantedBy=multi-user.target ``` -------------------------------- ### Add OpenAPI description to route Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/route-modifiers.md Use describe to provide a description for the route in generated OpenAPI documentation. ```ring @get("/users", func { ... }) describe("Get all users") ``` -------------------------------- ### @options(cPath, fHandler) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/routing.md Registers an OPTIONS route to handle incoming OPTIONS requests at the specified path. ```APIDOC ## @options(cPath, fHandler) ### Description Registers an OPTIONS route. ### Parameters - **cPath** (string) - Required - The URL path to match. - **fHandler** (function) - Required - The handler function to execute. ``` -------------------------------- ### Run the Bolt application Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/your-first-app.md Executes the application script using the Ring interpreter. ```bash ring app.ring ``` -------------------------------- ### setHost(cValue) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-configuration.md Sets the bind address for the server. ```APIDOC ## setHost(cValue) ### Description Sets the bind address for the server. The default is "0.0.0.0". ### Parameters - **cValue** (string) - Required - The IP address or hostname to bind. ``` -------------------------------- ### Set API Documentation Metadata Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/openapi-documentation.md Configures the title, version, and description displayed in the API documentation. ```ring setDocsInfo("My API", "1.0.0", "API for managing users") ``` -------------------------------- ### Render a template file Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/templates.md Use the renderFile method to process a template file with a provided data map. ```ring @get("/", func { html = $bolt.renderFile("templates/home.html", [ :title = "Welcome", :year = 2024, :user = [ :name = "John", :admin = true ], :items = [ [:name = "Widget", :price = 9.99], [:name = "Gadget", :price = 19.99] ] ]) $bolt.send(html) }) ``` -------------------------------- ### Configure Server Network Attributes Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-configuration.md Define the server port and bind address. ```ring port = 3000 # Server port (default: 3000) host = "0.0.0.0" # Bind address (default: "0.0.0.0") ``` -------------------------------- ### Hero Button Shortcode Implementation Source: https://github.com/ysdragon/bolt/blob/master/docs/site/layouts/_shortcodes/hextra/hero-button.html This template processes link, text, and style parameters to generate a formatted markdown link. ```html {{- $link := .Get "link" -}} {{- $text := .Get "text" -}} {{- $style := .Get "style" -}} {{- $external := hasPrefix $link "http" -}} {{- $path := strings.TrimSuffix "/" (replaceRE "^https?://[^/]+" "" site.BaseURL) -}} {{- $href := "" -}} {{- if $external -}} {{- $href = $link -}} {{- else if hasPrefix $link "/" -}} {{- $href = printf "%s%s" $path $link -}} {{- else -}} {{- $href = printf "%s/%s" $path $link -}} {{- end -}} [{{- $text -}}]({{ $href }}) ``` -------------------------------- ### Set Server Host Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-configuration.md Define the bind address for the server. ```ring setHost("127.0.0.1") ``` -------------------------------- ### Initialize Validate class Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/validate-class.md Create a new instance of the Validate class to access validation methods. ```ring v = new Validate ``` -------------------------------- ### before(cMiddlewareName) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/route-modifiers.md Adds a before middleware to the last registered route. ```APIDOC ## before(cMiddlewareName) ### Description Add a before middleware to the last registered route. ### Parameters - **cMiddlewareName** (string) - The name of the middleware to execute. ``` -------------------------------- ### Configure IP whitelist Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/security.md Adds specific IPs or CIDR ranges to the whitelist. ```ring ipWhitelist("192.168.1.100") ipWhitelist("10.0.0.0/8") ``` -------------------------------- ### $bolt.renderFile(cFilepath, aData) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/templates.md Renders a template file from the specified path and sends the result as the HTTP response. ```APIDOC ## $bolt.renderFile(cFilepath, aData) ### Description Render template from file and send as response. ### Parameters - **cFilepath** (string) - The path to the template file. - **aData** (map) - The data context to pass to the template. ### Example @get("/", func { $bolt.renderFile("templates/home.html", [:user = "John"]) }) ``` -------------------------------- ### File Responses Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md Methods for serving files from the server. ```APIDOC ## $bolt.sendFile(path) Sends a file with auto-detected MIME type. ## $bolt.sendFileAs(path, mimeType) Sends a file with an explicit MIME type. ``` -------------------------------- ### env.loadFile(cPath) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Loads environment variables from a specified file path. ```APIDOC ## env.loadFile(cPath) ### Description Loads environment variables from a specific file path provided as an argument. ### Parameters - **cPath** (string) - Required - The file path to the environment file. ### Usage ```ring env.loadFile("/etc/myapp/env") ``` ``` -------------------------------- ### Password Hashing with Hash Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/utility-classes.md Securely hash and verify passwords using Argon2, bcrypt, or scrypt algorithms. ```ring hash = new Hash # Argon2id (recommended) hashed = hash.argon2("mypassword") if hash.verifyArgon2("mypassword", hashed) # Password correct ok # Bcrypt hashed = hash.bcrypt("mypassword") if hash.verifyBcrypt("mypassword", hashed) # Password correct ok # Scrypt hashed = hash.scrypt("mypassword") if hash.verifyScrypt("mypassword", hashed) # Password correct ok ``` ```ring load "bolt.ring" hash = new Hash storedHash = "" new Bolt() { port = 3000 @post("/register", func { data = $bolt.jsonBody() storedHash = hash.argon2(data[:password]) $bolt.json([:registered = true]) }) @post("/login", func { data = $bolt.jsonBody() if hash.verifyArgon2(data[:password], storedHash) $bolt.json([:success = true]) else $bolt.unauthorized() ok }) } ``` -------------------------------- ### Configure Production Security and Limits Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md Essential settings for production environments, including TLS, rate limiting, CORS, and CSRF protection. ```ring enableTls("cert.pem", "key.pem") ``` ```ring setBodyLimit(10 * 1024 * 1024) # Limit body size $bolt.rateLimit(100, 60) # Per-IP rate limiting ``` ```ring enableCors() corsOrigin("https://yourdomain.com") # Not "*" in production ``` ```ring enableCsrf("strong-secret") setCookieSecret("another-strong-secret") ``` -------------------------------- ### POST /users Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md Demonstrates parsing a JSON request body and returning a JSON response with a specific status code. ```APIDOC ## POST /users ### Description Parses a JSON body, validates required fields, and returns a 201 status code upon success. ### Method POST ### Endpoint /users ``` -------------------------------- ### POST /api/data Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md Demonstrates how to access request metadata such as HTTP method, path, headers, raw body, client IP, and request ID. ```APIDOC ## POST /api/data ### Description Retrieves various metadata associated with the current HTTP request. ### Method POST ### Endpoint /api/data ``` -------------------------------- ### POST /profile Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md Demonstrates retrieving multiple values for a single form field name. ```APIDOC ## POST /profile ### Description Retrieves all values for a specific form field, useful for checkboxes or multi-select inputs. ### Method POST ### Endpoint /profile ``` -------------------------------- ### @static(cUrlPath, cDirPath) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/routing.md Serves static files from a specified directory. ```APIDOC ## @static(cUrlPath, cDirPath) ### Description Serves static files from a directory. ### Parameters - **cUrlPath** (string) - Required - The URL path prefix. - **cDirPath** (string) - Required - The local directory path. ``` -------------------------------- ### Write to server log at default level Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/logging.md Use this method to output a message to the server log using the default logging level. ```ring $bolt.log("User logged in: " + userId) ``` -------------------------------- ### Implement Basic Authentication in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/authentication.md Uses a @before hook to intercept requests and validate credentials against a hardcoded username and password. ```ring @before(func { # Skip public routes if $bolt.path() = "/" or $bolt.path() = "/public" return ok auth = $bolt.header("Authorization") if auth = "" or left(auth, 6) != "Basic " $bolt.setHeader("WWW-Authenticate", 'Basic realm="Protected"') $bolt.unauthorized() return ok # Decode credentials creds = $bolt.basicAuthDecode(auth) if creds = NULL $bolt.unauthorized() return ok username = creds[:username] password = creds[:password] if username != "admin" or password != "secret" $bolt.unauthorized() ok }) ``` -------------------------------- ### Set a cookie with default path Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/cookies.md Sets a cookie with the default path set to root. ```ring $bolt.setCookie("user", "john") ``` -------------------------------- ### env.loadEnv() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Loads environment variables from a .env file located in the current directory. ```APIDOC ## env.loadEnv() ### Description Loads the .env file from the current directory. This method is called automatically upon initialization. ### Usage ```ring env.loadEnv() ``` ``` -------------------------------- ### $bolt.queryAll(cName) Source: https://github.com/ysdragon/bolt/blob/master/docs/API.md Retrieves all values for a query parameter. ```APIDOC ## $bolt.queryAll(cName) ### Description Retrieves all values for a specific query parameter as a list. ### Parameters - **cName** (string) - The name of the query parameter. ### Usage ```ring tags = $bolt.queryAll("tag") ``` ``` -------------------------------- ### Configure proxy whitelist Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/security.md Adds an IP address to the proxy whitelist. ```ring proxyWhitelist("10.0.0.1") ``` -------------------------------- ### Retrieve file metadata with $bolt.file(nIndex) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/file-uploads.md Accesses file details by a 1-based index, returning a list containing the name, field, type, and size. ```ring f = $bolt.file(1) ? f[:name] # "photo.jpg" ? f[:field] # "avatar" ? f[:type] # "image/jpeg" ? f[:size] # 102400 ``` -------------------------------- ### $bolt.basicAuthEncode(cUsername, cPassword) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/authentication.md Encodes username and password into a Basic Auth string. ```APIDOC ## $bolt.basicAuthEncode(cUsername, cPassword) ### Description Encode Basic Auth credentials. ### Parameters - **cUsername** (string) - Required - The username. - **cPassword** (string) - Required - The password. ``` -------------------------------- ### Implement Copy to Clipboard Functionality Source: https://github.com/ysdragon/bolt/blob/master/examples/advanced/templates/layout.html Handles copying code block content to the clipboard and provides visual feedback. ```javascript function copyCode(btn) { var pre = btn.closest('.code-block').querySelector('pre'); var text = pre.textContent; navigator.clipboard.writeText(text).then(function () { btn.textContent = 'Copied!'; btn.classList.add('copied'); setTimeout(function () { btn.textContent = 'Copy'; btn.classList.remove('copied'); }, 2000); }); } ``` -------------------------------- ### describe(cDescription) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/route-modifiers.md Adds a description to the route for OpenAPI documentation. ```APIDOC ## describe(cDescription) ### Description Adds a description for OpenAPI docs. ### Parameters - **cDescription** (string) - The description text. ``` -------------------------------- ### Manage Basic Cookies in Ring Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/cookies-sessions.md Demonstrates setting, reading, and deleting cookies using the Bolt framework. ```ring # Set cookie @get("/set-cookie", func { $bolt.setCookie("username", "john") $bolt.send("Cookie set!") }) # Read cookie @get("/get-cookie", func { username = $bolt.cookie("username") if username != "" $bolt.send("Hello, " + username) else $bolt.send("No cookie found") ok }) # Delete cookie @get("/delete-cookie", func { $bolt.deleteCookie("username") $bolt.send("Cookie deleted!") }) ``` -------------------------------- ### Handle Multi-value Query Parameters Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/route-parameters.md Retrieve multiple values for the same query key as a list using $bolt.queryAll. ```ring @get("/search", func { tags = $bolt.queryAll("tag") # ["rust", "web"] $bolt.json([:tags = tags]) }) ``` -------------------------------- ### Access Route Parameters Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/GettingStarted/routing-basics.md Shows how to capture dynamic segments from a URL path using the $bolt.param() method. ```ring # Single parameter @get("/users/:id", func { userId = $bolt.param("id") $bolt.json([:id = userId]) }) # Multiple parameters @get("/posts/:postId/comments/:commentId", func { postId = $bolt.param("postId") commentId = $bolt.param("commentId") $bolt.json([ :postId = postId, :commentId = commentId ]) }) ``` -------------------------------- ### $bolt.query(cName) and $bolt.queryAll(cName) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/request.md Retrieves query string parameters. ```APIDOC ## $bolt.query(cName) ### Description Returns the first value of a query string parameter. ## $bolt.queryAll(cName) ### Description Returns all values for a query parameter as a list. ``` -------------------------------- ### $bolt.files() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/file-uploads.md Retrieves a list of all uploaded files. ```APIDOC ## $bolt.files() ### Description Get all uploaded files as a list of file lists. ### Returns - **files** (list) - A list of lists, where each inner list contains file metadata. ``` -------------------------------- ### $bolt.rateLimit(nMax, nWindow) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/rate-limiting.md Configures the per-IP rate limiting threshold. Each client IP is tracked independently. ```APIDOC ## $bolt.rateLimit(nMax, nWindow) ### Description Configures per-IP rate limiting. Each client IP gets its own counter. ### Parameters - **nMax** (number) - Required - The maximum number of requests allowed. - **nWindow** (number) - Required - The time window in seconds for the request limit. ### Example $bolt.rateLimit(100, 60) # 100 requests per 60 seconds per IP ``` -------------------------------- ### Configure Rate Limiting Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Guides/security.md Apply global or route-specific rate limits to prevent abuse. ```ring new Bolt() { port = 3000 # Per-IP: 100 requests per minute per client IP $bolt.rateLimit(100, 60) @before(func { if !$bolt.checkRateLimit() $bolt.setHeader("Retry-After", "60") $bolt.sendWithStatus(429, "Too many requests") ok }) @get("/api/data", func { $bolt.json([:data = "..."]) }) # Per-route rate limiting @post("/api/login", func { # Login logic... }) routeRateLimit(5, 60) # 5 attempts per minute } ``` -------------------------------- ### prefix(cPrefix) / endPrefix() Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/route-modifiers.md Groups routes under a common URL prefix. ```APIDOC ## prefix(cPrefix) / endPrefix() ### Description Groups routes under a common prefix. ### Parameters - **cPrefix** (string) - The URL prefix to apply to all routes within the block. ``` -------------------------------- ### Route Parameters Source: https://github.com/ysdragon/bolt/blob/master/docs/USAGE.md How to define routes with dynamic URL parameters and retrieve them using $bolt.param(). ```APIDOC ## GET /users/:id ### Description Retrieves a user by their ID. ### Endpoint /users/:id ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Response #### Success Response (200) - **id** (string) - The user ID provided in the URL. ``` -------------------------------- ### Set environment variable Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/env-class.md Assign a value to an environment variable. ```ring env.setVar("APP_ENV", "production") ``` -------------------------------- ### $bolt.cacheGet(cKey) Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/caching.md Retrieves a value from the cache by its key. ```APIDOC ## $bolt.cacheGet(cKey) ### Description Retrieve value from cache. Returns an empty string if the key is not found. ### Parameters - **cKey** (string) - The key to retrieve. ### Example data = $bolt.cacheGet("user:123") ``` -------------------------------- ### Client-side SSE subscription Source: https://github.com/ysdragon/bolt/blob/master/docs/site/content/docs/Reference/server-sent-events.md Standard browser implementation for connecting to an SSE endpoint and listening for messages. ```javascript const es = new EventSource('/events'); es.onmessage = (e) => console.log(e.data); es.addEventListener('update', (e) => console.log(e.data)); ```