### Running the Redbean Server (Shell) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This command executes the packaged Redbean application, starting the web server. It assumes the `redbean.com` file is in the current directory and has executable permissions. ```sh ./redbean.com ``` -------------------------------- ### Creating a Basic Fullmoon Web Application (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This Lua snippet demonstrates the simplest Fullmoon application. It loads the `fullmoon` module, defines a route for `/hello` that returns 'Hello, world', and then starts the Fullmoon server to handle incoming requests. ```lua local fm = require "fullmoon" -- (1) fm.setRoute("/hello", function(r) return "Hello, world" end) -- (2) fm.run() -- (3) ``` -------------------------------- ### Ordering Specific and General Routes in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example highlights the importance of route order, showing that more specific routes like /user/bob must be registered before more general routes like /user/:name to ensure they are evaluated correctly and not overshadowed. ```Lua fm.setRoute("/user/bob", handlerBob) fm.setRoute("/user/:name", handlerName) ``` -------------------------------- ### Creating a Basic Fullmoon Application with Routing and Templating - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates a complete Fullmoon application. It initializes the framework, defines a template named 'hello' that accepts a 'name' parameter, sets up a route '/hello/:name' to render this template using the provided name from the URL parameters, and finally starts the Fullmoon server. After packaging with Redbean, it serves 'Hello, world' for requests to http://localhost:8080/hello/world. ```Lua local fm = require "fullmoon" fm.setTemplate("hello", "Hello, {%& name %}") fm.setRoute("/hello/:name", function(r) return fm.serveContent("hello", {name = r.params.name}) end) fm.run() ``` -------------------------------- ### Registering and Rendering a Basic Template in Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example demonstrates how to register a template named "hello" with dynamic content and then render it. The `fm.setTemplate` function registers the template, while `fm.render` processes it, passing a table of parameters. The `{%& title %}` expression ensures the 'title' parameter's value is HTML-escaped before output. ```Lua fm.setTemplate("hello", "Hello, {%& title %}!") fm.render("hello", {title = "World"}) ``` -------------------------------- ### Defining Multiple Routes with a Single Call in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example shows how to register multiple routes (/route1, /route2) that share the same conditions and action handler using a single fm.setRoute call, simplifying route definition when common logic applies. ```Lua fm.setRoute({"/route1", "/route2"}, handler) ``` -------------------------------- ### Restricting Route to GET Method with Shorthand in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates a shorthand syntax in Fullmoon to define a route that only responds to HTTP GET requests. It captures an optional 'name' parameter from the URL and uses it to construct a greeting message. Requests with non-GET methods will fall through to other routes. ```Lua fm.setRoute(fm.GET"/hello(/:name)", function(r) return "Hello, "..(r.params.name or "World!") end) ``` -------------------------------- ### Setting Repeatable Response Headers - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet shows how to set a repeatable response header with multiple values. Values should be provided as a comma-separated string, which will be formatted correctly in the response header, for example, 'Allow: GET, POST'. ```Lua r.headers.Allow = "GET, POST" ``` -------------------------------- ### Nesting Templates with `render` Function in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example shows how one template (`header`) can render another template (`hello`) using the `render` function available within templates. Parameters can be passed from the outer template to the inner one, enabling complex layout structures. ```Lua fm.setTemplate("hello", "Hello, {%& title %}!") fm.setTemplate("header", "

{% render('hello', {title = title}) %}

") ---------------------------------└──────────────────────────────┘---------- fm.render("header", {title = 'World'}) -- renders `

Hello, World!

` ``` -------------------------------- ### Defining and Using External Routes for Path Generation in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example demonstrates how to define an "external" route that is only used for URL generation (without an action handler) and then use fm.makePath with its routeName to construct external URLs with dynamic parameters. ```Lua fm.setRoute({"https://youtu.be/:videoid", routeName = "youtube"}) fm.makePath("youtube", {videoid = "abc"}) --> https://youtu.be/abc ``` -------------------------------- ### Handling Dynamic URL Parameters and Serving Assets in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example shows how to use named parameters in Fullmoon routes to resolve 'nice' URLs to their HTML versions. The first route redirects '/blog/:file' to '/new-blog/:file.html'. The second route is crucial for serving the 'original' HTML assets, as the first rule only handles the redirection logic internally without triggering a client-side redirect. ```Lua fm.setRoute("/blog/:file", "/new-blog/:file.html") fm.setRoute("/new-blog/:file.html", fm.serveAsset) ``` -------------------------------- ### Restricting Route to GET Method with Table Syntax in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet shows an alternative, explicit table-based syntax for defining a Fullmoon route that is restricted to HTTP GET requests. It achieves the same outcome as the shorthand `fm.GET` syntax, capturing an optional 'name' parameter and returning a personalized greeting. ```Lua fm.setRoute({"/hello(/:name)", method = "GET"}, function(r) return "Hello, "..(r.params.name or "World!") end) ``` -------------------------------- ### Running Fullmoon Application with Custom Address and Port (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to execute a Fullmoon application using the `fm.run` method, explicitly setting the listening address to `localhost` and the port to `8080`. While these are the default values, this example shows the syntax for overriding them. The `addr` option specifies the network interface to bind to, and `port` defines the listening port number. This method supports numerous other configuration options for server behavior, caching, TLS, and logging. ```lua fm.run({addr = "localhost", port = 8080}) ``` -------------------------------- ### Setting Specific Condition Otherwise in Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example shows how to apply the `otherwise` condition to a specific route parameter, in this case, `ContentLength`. If only the `ContentLength` check fails, a 413 status code is returned, allowing other method failures to fall through to other routes. ```Lua fm.setRoute(fm.POST{"/upload", ContentLength = {isLessThan(100000), otherwise = 413} }, function(r) ...handle the upload... end) ``` -------------------------------- ### Setting Response Headers - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates how to set a custom response header. Assigning a string value to a header field in the `r.headers` table will include that header in the outgoing response. For example, 'MyHeader: value'. ```Lua r.headers.MyHeader = "value" ``` -------------------------------- ### Using Named Splat Parameters for Unique Routes in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example illustrates how to use named splat parameters (e.g., `*dosomething1`) to register multiple routes with similar paths without overwriting previous definitions. Each named splat creates a unique route, allowing separate action handlers for different logical operations, even if the base path is similar. ```Lua fm.setRoute("/*dosomething1", function(r) return "something 1" end) fm.setRoute("/*dosomething2", function(r) return "something 2" end) ``` -------------------------------- ### Configuring Method-Specific Otherwise Condition in Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates setting an `otherwise` condition specifically for method mismatches. If the endpoint is accessed with a method other than 'GET' or 'POST', a 405 status code is returned immediately, preventing further route checks. ```Lua fm.setRoute({"/hello(/:name)", method = {"GET", "POST", otherwise = 405}}, function(r) return "Hello, "..(r.params.name or "World!") end) ``` -------------------------------- ### Illustrating Nested Block Inheritance in Fullmoon Templates Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example demonstrates the inheritance behavior of nested blocks across multiple template levels (base, child, grandchild). It shows how a block defined in a child template overrides the parent's block, and how the rendering engine resolves which block definition to use based on the current render tree, emphasizing the importance of definition order. ```Lua -- base/layout template {% function block.greet() %} -- 1. defines default "greet" block Hi {% end %} {% block.greet() %} -- 2. calls "greet" block -- child template {% function block.greet() %} -- 3. defines "greet" block Hello {% end %} {% render('base') %} -- 4. renders "base" template -- grandchild template {% function block.greet() %} -- 5. defines "greet" block Bye {% end %} {% render('child') %} -- 6. renders "child" template ``` -------------------------------- ### Restricting Route to Multiple HTTP Methods in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to configure a Fullmoon route to respond to multiple HTTP methods, specifically GET and POST, by providing a table of methods. It allows the route to handle requests from either method, capturing an optional 'name' parameter for a personalized response. ```Lua fm.setRoute({"/hello(/:name)", method = {"GET", "POST"}}, function(r) return "Hello, "..(r.params.name or "World!") end) ``` -------------------------------- ### Registering a Cron Job Schedule with Fullmoon Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to register a scheduled job using `fm.setSchedule` with cron syntax. It shows a basic example of a job that logs "every minute", explaining the cron fields (minute, hour, day of month, month, day of week). By default, functions are executed in a separate forked process, but can be run in the same process by passing `{sameProc = true}` as a third parameter. ```lua --------------- ┌─────────── minute (0-59) --------------- │ ┌───────── hour (0-23) --------------- │ │ ┌─────── day of the month (1-31) --------------- │ │ │ ┌───── month (1-12 or Jan-Dec) --------------- │ │ │ │ ┌─── day of the week (0-6 or Sun-Mon) --------------- │ │ │ │ │ -- --------------- │ │ │ │ │ -- fm.setSchedule("* * * * *", function() fm.logInfo("every minute") end) ``` -------------------------------- ### Accessing Registered Request Headers (Case-Sensitive) - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet shows how to access registered request headers using dot notation. This method is case-sensitive and requires the capitalization to be preserved as registered. It returns the value of the specified header, for example, 'ContentType'. ```Lua r.headers.ContentType ``` -------------------------------- ### Setting Route with Dynamic Function Validator for Content Length - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example illustrates creating a dynamic validator function (`isLessThan`) that returns another function. This returned function is then used with `fm.setRoute` to validate the `ContentLength` header for POST requests, ensuring that uploaded content does not exceed a specified size (100000 bytes). ```Lua local function isLessThan(n) return function(l) return tonumber(l) < n end end fm.setRoute(fm.POST{"/upload", ContentLength = isLessThan(100000)}, function(r) ...handle the upload... end) ``` -------------------------------- ### Custom 404 Error Handling in Fullmoon Action Handler - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example illustrates how to trigger a custom 404 (Not Found) error response from within an action handler or a function called by it. The `AnyOr404` helper function checks if a database result is `nil` or `db.NONE`, and if so, it uses `error(fm.serve404)` to immediately return a 404 status code to the client, bypassing further processing. ```Lua local function AnyOr404(res, err) if not res then error(err) end -- serve 404 when no record is returned if res == db.NONE then error(fm.serve404) end return res, err end fm.setRoute("/", function(r) local row = AnyOr404(dbm:fetchOne("SELECT id FROM test")) return row.id end) ``` -------------------------------- ### Accessing Global Template Variables with `vars` in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example illustrates how to set a global template variable using `fm.setTemplateVar` and then access it from within any template via the `vars` table (e.g., `vars.title`). This allows sharing values across multiple templates. ```Lua fm.setTemplateVar('title', 'World') fm.setTemplate("hello", "Hello, {%& vars.title %}!") fm.render("hello") -- renders `Hello, World!` ``` -------------------------------- ### Returning a Custom HTTP Response in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This example shows how to use `fm.serveResponse` to send a custom HTTP response. It returns a 413 status code with 'Payload Too Large' as the response body, indicating that the request entity is larger than the server is willing or able to process. ```Lua return fm.serveResponse(413, "Payload Too Large") ``` -------------------------------- ### Defining Custom Parameter Validation with Character Classes in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet shows how to define a custom route parameter `:id` that only matches digits (`%d`) using Lua character classes. The parameter is also optional, similar to the first example. If the parameter is not provided or doesn't match the digit pattern, `r.params.id` will be `false`, allowing a fallback to 'World!'. ```Lua fm.setRoute("/hello(/:id[%d])", function(r) return "Hello, "..(r.params.id or "World!") end) ``` -------------------------------- ### Packaging Fullmoon Application with Redbean (Shell) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This command zips the Fullmoon application's initialization script (`.init.lua`) and the Fullmoon core library (`.lua/fullmoon.lua`) into the `redbean.com` executable, creating a self-contained application. If application code is in a separate file, it should also be included in the zip. ```sh zip redbean.com .init.lua .lua/fullmoon.lua ``` -------------------------------- ### Loading Fullmoon Showcase Module in Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This Lua snippet demonstrates how to load the 'showcase' module, which subsequently loads its 'fullmoon' dependency, from specific file paths within a redbean executable/archive. This configuration is typically placed in the `.init.lua` file to initialize the application upon startup. ```Lua -- this is the content of .init.lua require "showcase" -- this loads `showcase` module from `.lua/showcase.lua` file, -- which also loads its `fullmoon` dependency from `.lua/fullmoon.lua` ``` -------------------------------- ### Benchmarking Fullmoon Routing and Template Processing (Redbean optlinux) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet runs a `wrk` benchmark against a Fullmoon application, similar to the previous test, but with redbean compiled using the `MODE=optlinux` option. It uses 12 threads and 120 connections to `http://127.0.0.1:8080/user/paul` to evaluate performance under optimized redbean compilation. ```Shell $ wrk -t 12 -c 120 http://127.0.0.1:8080/user/paul ``` -------------------------------- ### Downloading and Making Redbean Executable (Shell) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This command sequence downloads the Redbean executable from its official site and then makes it executable on Unix-like systems. The `chmod +x` command should be skipped if running these commands on Windows. ```sh curl -o redbean.com https://redbean.dev/redbean-2.2.com chmod +x redbean.com ``` -------------------------------- ### Configuring Routes for Static Assets and Directory Index in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to configure routes in Fullmoon to serve static assets and directory indexes. The first line maps all requests under `/static/*` to be served by `fm.serveAsset`, while the second line configures `/blog/` to serve an `index.lua` or `index.html` from the `/new-blog/` directory. ```Lua fm.setRoute("/static/*", fm.serveAsset) fm.setRoute("/blog/", fm.serveIndex("/new-blog/")) ``` -------------------------------- ### Setting Basic Route in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a basic route in Fullmoon that matches an exact path. It sets up a handler for the '/hello' path, which responds with 'Hello, World!' to incoming requests. This route does not match partial paths or paths with additional segments. ```Lua fm.setRoute("/hello", function(r) return "Hello, World!" end) ``` -------------------------------- ### Implementing a Catch-All Route in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a catch-all route (/*catchall) using fm.servePath to handle requests that do not match any explicitly registered routes, preventing 404 errors for dynamic content or unrouted requests. ```Lua fm.setRoute("/*catchall", fm.servePath) ``` -------------------------------- ### Benchmarking Fullmoon Routing and Template Processing (Standard) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet executes a `wrk` benchmark against a Fullmoon application, testing routing, parameter handling, and template processing. It uses 12 threads and 120 connections to `http://127.0.0.1:8080/user/paul`. The template uses `{%= name %}` to skip HTML escaping. ```Shell $ wrk -t 12 -c 120 http://127.0.0.1:8080/user/paul ``` -------------------------------- ### Serving Static Template Content: render vs. serveContent in Fullmoon Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates the difference between `fm.render` and `fm.serveContent` when serving static templates. It highlights that `fm.render` is executed immediately when the route is set up, leading to incorrect behavior for static content, whereas `fm.serveContent` delays processing until the request is handled, ensuring the template is rendered correctly at runtime. ```lua fm.setTemplate("hello", "Hello, World!") -- option 1: fm.setRoute("/hello", fm.render("hello")) -------------------------└─────┘-------- not going to work -- option 2: fm.setRoute("/hello", fm.serveContent("hello")) -------------------------└───────────┘-- works as expected ``` -------------------------------- ### Benchmarking Redbean Static Compressed Asset Latency Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet benchmarks redbean's performance when serving static compressed assets. It uses `wrk` with a single thread and connection, including an `Accept-Encoding: gzip` header, to measure latency for `htt://10.10.10.124:8080/tool/net/demo/index.html`. ```Shell $ wrk -H 'Accept-Encoding: gzip' -t 1 -c 1 htt://10.10.10.124:8080/tool/net/demo/index.html ``` -------------------------------- ### Serving Dynamic Template Content with Fullmoon Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a dynamic template and serve its output using `fm.serveContent` within a route handler. It shows how to pass parameters from the request (`r.params.name`) to the template. `fm.serveContent` allows the action handler to complete after serving the content, similar to `fm.render` but with a delayed processing mechanism. ```lua fm.setTemplate("hello", "Hello, {%& name %}") fm.setRoute("/hello/:name", function(r) return fm.serveContent("hello", {name = r.params.name}) end) ``` -------------------------------- ### Defining Multiple Routes Individually in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates the equivalent individual fm.setRoute calls for registering multiple routes, demonstrating that the previous single-call method is a syntactic sugar for these separate definitions. ```Lua fm.setRoute("/route1", handler) fm.setRoute("/route2", handler) ``` -------------------------------- ### Dynamically Selecting Templates for Rendering in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates how to dynamically choose which template to render by passing the template's name as a parameter. The `header` template uses the `content` parameter to decide whether to render `hello` or `bye`, allowing for flexible layout composition. ```Lua fm.setTemplate("hello", "Hello, {%& title %}!") fm.setTemplate("bye", "Bye, {%& title %}!") fm.setTemplate("header", "

{% render(content, {title = title}) %}

") fm.render("header", {title = 'World', content = 'hello'}) ``` -------------------------------- ### Creating a Reusable Modal Component with Fullmoon Blocks Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This code defines a `modal` template using Fullmoon blocks for its title, content, and action buttons. It establishes default content for `block.modal_title` and `block.modal_actions`, while `block.modal_content` is left to be defined by consuming templates, showcasing a modular component structure. ```Lua fm.setTemplate("modal", [[ ]]) ``` -------------------------------- ### Handling Multipart Parameters in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a route that processes multipart form data. It shows accessing a simple parameter (r.params.simple) and a multipart parameter's data (r.params.multipart.more.data), illustrating how Fullmoon makes multipart content accessible via the params.multipart table. ```Lua fm.setRoute({"/hello", simple = "value"}, function(r) return "Show "..r.params.simple.." "..r.params.multipart.more.data) end) ``` -------------------------------- ### Benchmarking Fullmoon Request Latency (No Concurrency) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet measures the latency of request handling by Fullmoon using `wrk` with no concurrency (1 thread, 1 connection). It targets `http://127.0.0.1:8080/user/paul` to demonstrate the minimum latency for a single request. ```Shell $ wrk -t 1 -c 1 http://127.0.0.1:8080/user/paul ``` -------------------------------- ### Defining and Referencing Blocks in Fullmoon Lua Templates Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define and override blocks within Fullmoon templates using `fm.setTemplate`. It shows how a block (`greet`) can be defined within one template (`header`) and then overridden in another (`bye`), while still allowing the original block to be referenced explicitly using `block..()`. It also illustrates template rendering with parameters. ```Lua fm.setTemplate("header", [[

{% function block.greet() %} Hi {% end %} {% block.greet() %}, {%& title %}!

]]) fm.setTemplate("bye", [[ {% block.header.greet() %}, {% function block.greet() %} Bye {% end %} {% render('header', {title=title}) %}! ]]) fm.render("bye", {title = 'World'}) -- renders `

Hi, Bye, World!

` ``` -------------------------------- ### Defining and Overriding Template Blocks in Fullmoon Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a default block (`block.greet`) in a parent template (`header`) and then override its content in child templates (`hello`, `bye`). It shows how `fm.render` uses the overridden block content when rendering the parent template through a child, illustrating template inheritance and content customization. ```Lua fm.setTemplate("header", [[

{% function block.greet() %} -- define a (default) block Hi {% end %} {% block.greet() %}, -- render the block {%& title %}!

]]) fm.setTemplate("hello", [[ {% function block.greet() %} -- overwrite the `header` block (if any) Hello {% end %} {% render('header', {title=title}) %}! ]]) fm.setTemplate("bye", [[ {% function block.greet() %} -- overwrite the `header` block (if any) Bye {% end %} {% render('header', {title=title}) %}! ]]) -- normally only one of the three `render` calls is needed, -- so all three are shown for illustrative purposes only fm.render("hello", {title = 'World'}) -- renders

Hello, World!

fm.render("bye", {title = 'World'}) -- renders `

Bye, World!

` fm.render("header", {title = 'World'}) -- renders `

Hi, World!

` ``` -------------------------------- ### Registering APE Interpreter for Redbean on Linux (Shell) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This command registers the APE (Actually Portable Executable) interpreter via `binfmt_misc` on Linux, resolving 'not finding interpreter' errors for Redbean. Note that this change might not persist across system restarts. ```sh sudo sh -c "echo ':APE:M::MZqFpD::/bin/sh:' >/proc/sys/fs/binfmt_misc/register" ``` -------------------------------- ### Chaining Action Handlers with Fullmoon Routes - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to chain multiple action handlers for a set of related routes in Fullmoon. The first handler acts as a "before" filter, retrieving user information and returning `false` to allow subsequent, more specific routes (like `/view` or `/edit`) to be processed. It also shows how to handle different HTTP methods and return a 405 status code if the method is not allowed. ```Lua local uroute = "/user/:id" fm.setRoute({uroute.."/*", method = {"GET", "POST", otherwise = 405}}, function(r) -- retrieve user information based on r.params.id -- and store in r.user (as one of the options); -- return error if user is not found return false -- continue handling end) fm.setRoute(fm.GET(uroute.."/view"), function(r) ... end) fm.setRoute(fm.GET(uroute.."/edit"), function(r) ... end) fm.setRoute(fm.POST(uroute.."/edit"), function(r) ... end) ``` -------------------------------- ### Returning a Specific HTTP Status Code using Shorthand in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates the shorthand syntax for returning a specific HTTP status code in Fullmoon. `fm.serve413` is a convenient alias for `fm.serveResponse(413, ...)` when only the status code needs to be set, simplifying error responses. ```Lua return fm.serve413 ``` -------------------------------- ### Setting Parameterized Route in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates how to define a route with a placeholder parameter in Fullmoon. The route '/hello/:name' captures the value following '/hello/' into the 'name' parameter, which is then accessed via `r.params.name` to construct a personalized greeting. This parameter matches one or more characters excluding '/'. ```Lua fm.setRoute("/hello/:name", function(r) return "Hello, "..(r.params.name) end) ``` -------------------------------- ### Defining Optional Route Parameters in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define an optional route parameter `:name` in Fullmoon by wrapping it in parentheses. If the parameter is not provided in the URL (e.g., /hello), `r.params.name` will be `false`, allowing a default value ('World!') to be used. It accepts paths like /hello and /hello/Bob. ```Lua fm.setRoute("/hello(/:name)", function(r) return "Hello, "..(r.params.name or "World!") end) ``` -------------------------------- ### Setting Default and Overriding Template Parameters in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define default parameters when registering a template using `fm.setTemplate` and how to override these defaults by passing new parameters during `fm.render`. It shows how `title` can be set globally or per-render. ```Lua fm.setTemplate("hello", "Hello, {%& title %}!", {title = "World"}) fm.render("hello") -- renders `Hello, World!` fm.render("hello", {title = "All"}) -- renders `Hello, All!` ``` -------------------------------- ### Redirecting URLs with Wildcard in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to set up an internal route in Fullmoon to redirect requests from one URL path to another using a wildcard. It redirects any resource under '/blog/' to '/new-blog/', provided the target resource exists. This is an internal re-routing, not a client-side redirect. ```Lua fm.setRoute("/blog/*", "/new-blog/*") ``` -------------------------------- ### Setting a Route for a Specific HTTP Status Code Handler in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This code demonstrates how to set a route that directly uses a `serve###` shorthand as an action handler. It configures a PUT request to `/status` to immediately return a 402 Payment Required status code, useful for API endpoints requiring specific payment conditions. ```Lua fm.setRoute(fm.PUT"/status", fm.serve402) ``` -------------------------------- ### Generating Paths with Named Routes in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet shows how to define routes with optional names (routeName) and then use the fm.makePath function to generate URLs based on either the route's URL pattern or its assigned name, dynamically populating parameter placeholders. ```Lua fm.setRoute("/user/:name", handlerName) fm.setRoute({"/post/:id", routeName = "post"}, handlerPost) fm.makePath("/user/:name", {name = "Bob"}) --> /user/Bob fm.makePath("/post/:id", {id = 123}) --> /post/123 fm.makePath("post", {id = 123}) --> /post/123, same as the previous one ``` -------------------------------- ### Retrieving Latest Redbean Version (Shell) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This command fetches the latest stable version number of Redbean from the official Redbean development server, useful for scripting updates or verifying current versions. ```sh curl https://redbean.dev/latest.txt ``` -------------------------------- ### Asserting Fullmoon Validator Result for Immediate Error Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates a concise way to handle validation failures by wrapping the validator call in an `assert` statement. If `validator(r.params)` returns `nil` (indicating a failure), `assert` will immediately throw an error, halting execution. This is useful when the script needs to stop processing and signal an error right away, preventing further actions if validation conditions are not met. ```Lua assert(validator(r.params)) -- throw an error if validation fails return fm.serveRedirect(307, "/") -- return redirect in other cases ``` -------------------------------- ### Setting Response Cookies with Attributes - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet shows how to set a response cookie along with its attributes. The value and attributes are passed as a table, allowing control over properties like `secure`, `httponly`, `expires`, `maxage`, `domain`, `path`, and `samesite`. Note that default `httponly` and `samesite='Strict'` are overwritten. ```Lua r.cookies.token = {"new value", secure = true, httponly = true} ``` -------------------------------- ### Disabling binfmt_misc for Redbean on WSL/WINE (Shell) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This command disables `binfmt_misc` on Linux, which can resolve puzzling errors when running Redbean 2.x on WSL or WINE environments. ```sh sudo sh -c 'echo -1 >/proc/sys/fs/binfmt_misc/status' ``` -------------------------------- ### Setting Route with Function Validator for IP Address - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a route in Fullmoon where a custom function (`fm.isLoopbackIp`) is used as a validator for the `clientAddr` parameter. It ensures that the route is only accessible if the client's IP address is a loopback address. ```Lua fm.setRoute({"/local-only", clientAddr = fm.isLoopbackIp}, function(r) return "Local content" end) ``` -------------------------------- ### Customizing Fullmoon Modal Blocks in a Child Template Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates how a child template (`page`) can override specific blocks (`block.modal_title`, `block.modal_content`) defined within a parent `modal` template. It demonstrates how `render('modal')` will then incorporate these customized block contents, allowing for dynamic customization of reusable components. ```Lua fm.setTemplate("page", [[ {% function block.modal_title() %} Insert photo {% end %} {% function block.modal_content() %}
Upload photo here
{% end %} {% render('modal') %} ]]) ``` -------------------------------- ### Configuring Undefined Value Handling with `if-nil` in Fullmoon (Lua) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to configure a custom handler for undefined template values using the `if-nil` template variable. When `vars.missing` is accessed and is undefined, the provided function is executed, causing an error to be thrown instead of silently rendering an empty string. ```Lua fm.setTemplateVar('if-nil', function() error"missing value" end) fm.setTemplate("hello", "Hello, {%& vars.missing %}!") fm.render("hello") -- throws "missing value" error ``` -------------------------------- ### Setting Simple Response Cookies - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates how to set a simple response cookie with a new value. Assigning a string directly to a cookie field in the `r.cookies` table will set that cookie in the outgoing response. ```Lua r.cookies.token = "new value" ``` -------------------------------- ### Accessing Session Values - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to retrieve a value from the session table. It returns the previously stored value associated with the specified key, such as 'counter'. ```Lua r.session.counter ``` -------------------------------- ### Integrating Fullmoon Validator with a Route (Implicit Error Handling) Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to define a form validator using `fm.makeValidator` for 'name' and 'password' fields with minimum/maximum length constraints and custom error messages. The validator is then directly integrated into a `fm.POST` route definition. If validation fails, the route's handler is skipped, and the request is implicitly handled by Fullmoon's default error mechanism, typically preventing the route from executing. ```Lua local validator = fm.makeValidator{ {"name", minlen = 5, maxlen = 64, msg = "Invalid %s format"}, {"password", minlen = 5, maxlen = 128, msg = "Invalid %s format"}, } fm.setRoute(fm.POST{"/signin", _ = validator}, function(r) -- do something useful with name and password return fm.serveRedirect(307, "/") end) ``` -------------------------------- ### Setting Session Values - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet illustrates how to set or update a value in the session table. Any Lua value, including nested tables, can be assigned to a session key, which will be persisted across requests. ```Lua r.session.counter = 2 ``` -------------------------------- ### Removing Session - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to remove the entire session. Assigning an empty table `{}` or `nil` to the `r.session` object will invalidate and remove the current user's session data. ```Lua r.session = {} r.session = nil ``` -------------------------------- ### Accessing Request Headers (Case-Insensitive) - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to access request headers using bracket notation, which provides case-insensitive access to header values. It returns the value of the specified header, such as 'Content-Type'. ```Lua r.headers["Content-Type"] ``` -------------------------------- ### Setting Route-Level Otherwise Condition in Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to set a route-level `otherwise` condition in Fullmoon. If any condition (method or Content-Length) fails, a 413 status code is returned. It uses a custom `isLessThan` validator for the `Content-Length` header. ```Lua local function isLessThan(n) return function(l) return tonumber(l) < n end end fm.setRoute(fm.POST{"/upload", ContentLength = isLessThan(100000), otherwise = 413 }, function(r) ...handle the upload... end) ``` -------------------------------- ### Calling Fullmoon Validator Directly in a Route Handler Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates an alternative approach where the validator is not directly bound to the route but is instead called explicitly within the route's action handler. The `validator` function is invoked with `r.params` (request parameters) and returns `true` on success or `nil, error` on failure. This allows for conditional logic within the handler to serve a redirect on success or render an error page on validation failure. ```Lua local validator = fm.makeValidator{ {"name", minlen = 5, maxlen = 64, msg = "Invalid %s format"}, {"password", minlen = 5, maxlen = 128, msg = "Invalid %s format"}, } fm.setRoute(fm.POST{"/signin"}, function(r) local valid, error = validator(r.params) if valid then return fm.serveRedirect("/") -- status code is optional else return fm.serveContent("signin", {error = error}) end end) ``` -------------------------------- ### Removing Response Headers - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to remove a previously set response header. Assigning `nil` to a header field in the `r.headers` table will prevent that header from being sent in the response. ```Lua r.headers.MyHeader = nil ``` -------------------------------- ### Accessing Request Cookies - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to access the value of a specific request cookie. It returns the string value associated with the cookie name, such as 'token'. ```Lua r.cookies.token ``` -------------------------------- ### Customizing Fullmoon Validator Error Handling with 'otherwise' Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet extends the validator definition by adding an `otherwise` function. This function acts as a custom error handler that is invoked when any validation check fails. It receives the error message (or a table of messages if `all` option is used) and allows the application to render a specific view, such as a sign-in page with the error displayed, instead of relying on default error handling. ```Lua local validator = fm.makeValidator{ {"name", minlen = 5, maxlen = 64, msg = "Invalid %s format"}, {"password", minlen = 5, maxlen = 128, msg = "Invalid %s format"}, otherwise = function(error) return fm.serveContent("signin", {error = error}) end, } ``` -------------------------------- ### Deleting Response Cookies - Fullmoon - Lua Source: https://github.com/pkulchenko/fullmoon/blob/master/README.md This snippet demonstrates how to delete a specific response cookie. Assigning `false` to a cookie field in the `r.cookies` table will instruct the client to remove that cookie. ```Lua r.cookies.token = false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.