FullMoon เป็นเฟรมเวิร์กเว็บที่รวดเร็วและเรียบง่ายโดยใช้ RedBean ซึ่งเป็นเว็บเซิร์ฟเวอร์แบบพกพาแบบพกพาแบบพกพาได้
ทุกสิ่งที่จำเป็นสำหรับการพัฒนาและการกระจายมาในไฟล์เดียวที่ไม่มีการพึ่งพาภายนอกและหลังจากบรรจุภัณฑ์ที่มี RedBean ทำงานบน Windows, Linux หรือ MacOS ต่อไปนี้เป็นตัวอย่างที่สมบูรณ์ของแอปพลิเคชัน FullMoon:
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 ()
หลังจากบรรจุด้วย RedBean แล้วก็สามารถเปิดตัวได้โดยใช้ ./redbean.com
ซึ่งเริ่มต้นเซิร์ฟเวอร์ที่ส่งคืน "Hello, World" ไปยังคำขอ HTTP (s) ที่ส่งไปยัง http: // localhost: 8080/hello/world
RedBean เป็นเว็บเซิร์ฟเวอร์ cross-platform แบบกระจายไฟล์เดียวที่มีคุณสมบัติที่ไม่ซ้ำกันและทรงพลัง ในขณะที่มีเฟรมเวิร์กเว็บที่ใช้ Lua หลายแห่ง (Lapis, Lor, Sailor, Pegasus และอื่น ๆ ) ไม่มีใครรวมเข้ากับ Redbean (แม้ว่าจะมีกรอบการทดลอง Anpan)
Fullmoon เป็นกรอบเว็บที่มีน้ำหนักเบาและเรียบง่ายซึ่งเขียนจากมุมมองของการจัดแสดงความสามารถทั้งหมดที่ Redbean จัดเตรียมโดยการขยายและเพิ่มพวกเขาในวิธีที่ง่ายที่สุดและมีประสิทธิภาพมากที่สุด มันทำงานได้อย่างรวดเร็วและมาพร้อมกับแบตเตอรี่ (เส้นทาง, เทมเพลต, การสร้าง JSON และอื่น ๆ )
Fullmoon ติดตามปรัชญา Lua และจัดหาชุดเครื่องมือที่น้อยที่สุดเพื่อรวมตามที่ต้องการและใช้เป็นพื้นฐานในการสร้าง
fork
socket
หน่วยความจำที่ใช้ร่วมกันและอื่น ๆดาวน์โหลดสำเนาของ RedBean โดยเรียกใช้คำสั่งต่อไปนี้ (ข้ามคำที่สองหากเรียกใช้คำสั่งเหล่านี้บน Windows):
curl -o redbean.com https://redbean.dev/redbean-2.2.com
chmod +x redbean.com
หมายเลขเวอร์ชันล่าสุดสามารถเรียกดูได้ด้วยคำขอต่อไปนี้:
curl https://redbean.dev/latest.txt
อีกทางเลือกหนึ่งคือการสร้าง RedBean จากแหล่งที่มาโดยทำตามคำแนะนำสำหรับการสร้างแหล่งที่มา
fullmoon.lua
ไปยัง .lua/
directory.init.lua
(ตัวอย่างเช่นรหัส LUA ที่แสดงในคำอธิบาย) อีกทางเลือกหนึ่งคือการวางรหัสแอปพลิเคชันลงในไฟล์แยกต่างหาก (ตัวอย่างเช่น .lua/myapp.lua
) และเพิ่ม require "myapp"
ไปที่ .init.lua
นี่คือวิธีการนำเสนอตัวอย่างทั้งหมด
zip redbean.com .init.lua .lua/fullmoon.lua
หากรหัสแอปพลิเคชันถูกเก็บไว้ในไฟล์ LUA แยกต่างหากตามที่อธิบายไว้ข้างต้นตรวจสอบให้แน่ใจว่าได้วางไว้ใน .lua/
ไดเรกทอรีและซิปไฟล์นั้นเช่นกัน
./redbean.com
หากคำสั่งนี้ดำเนินการบน Linux และส่งข้อผิดพลาดเกี่ยวกับการไม่ค้นหาล่ามควรได้รับการแก้ไขโดยเรียกใช้คำสั่งต่อไปนี้ (แม้ว่าโปรดทราบว่าอาจไม่รอดจากการรีสตาร์ทระบบ):
sudo sh -c " echo ':APE:M::MZqFpD::/bin/sh:' >/proc/sys/fs/binfmt_misc/register "
หากคำสั่งนี้ก่อให้เกิดข้อผิดพลาดที่ทำให้งงใน WSL หรือไวน์เมื่อใช้ RedBean 2.x พวกเขาอาจได้รับการแก้ไขโดยการปิดใช้งาน BINFMT_MISC:
sudo sh -c ' echo -1 >/proc/sys/fs/binfmt_misc/status '
เปิดตัวเบราว์เซอร์ชี้ไปที่ http: // localhost: 8080/hello/world และควรกลับ "Hello, World" (สมมติว่าแอปพลิเคชันกำลังใช้รหัสที่แสดงในบทนำหรือหนึ่งในส่วนการใช้งาน)
ตัวอย่างที่ง่ายที่สุดจำเป็นต้อง (1) โหลดโมดูล (2) กำหนดค่าเส้นทางหนึ่งเส้นทางและ (3) เรียกใช้แอปพลิเคชัน:
local fm = require " fullmoon " -- (1)
fm . setRoute ( " /hello " , function ( r ) return " Hello, world " end ) -- (2)
fm . run () -- (3)
แอปพลิเคชันนี้ตอบสนองต่อคำขอ /hello
URL ใด ๆ ด้วยการส่งคืนเนื้อหา "Hello, World" (และรหัสสถานะ 200) และตอบกลับด้วยรหัสสถานะ 404 สำหรับคำขออื่น ๆ ทั้งหมด
setRoute(route[, action])
: ลงทะเบียนเส้นทาง หาก route
เป็นสตริงจะใช้เป็นนิพจน์เส้นทางเพื่อเปรียบเทียบเส้นทางคำขอกับ หากเป็นตารางองค์ประกอบของมันจะเป็นสตริงที่ใช้เป็นเส้นทางและค่าแฮชของมันคือเงื่อนไขที่เส้นทางถูกตรวจสอบ หากพารามิเตอร์ที่สองเป็นฟังก์ชั่นแสดงว่าจะดำเนินการหากเงื่อนไขทั้งหมดเป็นที่พอใจ หากเป็นสตริงมันจะถูกใช้เป็นนิพจน์เส้นทางและคำขอจะถูกประมวลผลราวกับว่ามันถูกส่งไปที่เส้นทางที่ระบุ (ทำหน้าที่เป็นการเปลี่ยนเส้นทางภายใน) หากเงื่อนไขใด ๆ ไม่พอใจจะมีการตรวจสอบเส้นทางต่อไป นิพจน์เส้นทางสามารถมีพารามิเตอร์หลายตัวและชิ้นส่วนเสริม ตัวจัดการการกระทำยอมรับตารางคำขอที่ให้การเข้าถึงการร้องขอและพารามิเตอร์เส้นทางรวมถึงส่วนหัวคุกกี้และเซสชัน
setTemplate(name, template[, parameters])
: ลงทะเบียนเทมเพลตที่มีชื่อที่ระบุหรือชุดของเทมเพลตจากไดเรกทอรี หาก template
เป็นสตริงก็จะรวบรวมไว้ในตัวจัดการเทมเพลต หากเป็นฟังก์ชั่นมันจะถูกจัดเก็บและเรียกเมื่อทำการร้องขอเทมเพลต หากเป็นตารางองค์ประกอบแรกของมันคือเทมเพลตหรือฟังก์ชั่นและส่วนที่เหลือจะใช้เป็นตัวเลือก ตัวอย่างเช่นการระบุ ContentType
เป็นหนึ่งในตัวเลือกตั้งค่าส่วนหัว Content-Type
สำหรับเนื้อหาที่สร้างขึ้น เทมเพลตหลายรายการ ( 500
, json
และอื่น ๆ ) มีให้โดยค่าเริ่มต้นและสามารถเขียนทับได้ parameters
คือตารางที่มีพารามิเตอร์เทมเพลตที่เก็บไว้เป็นคู่ชื่อ/ค่า (อ้างอิงเป็นตัวแปรในเทมเพลต)
serveResponse(status[, headers][, body])
: ส่งการตอบกลับ HTTP โดยใช้ status
ที่ให้มา headers
และค่า body
headers
เป็นตารางเสริมที่มีชื่อ HTTP ส่วนหัว/คู่ค่า หากมีให้ชุดส่วนหัวนี้ จะลบส่วนหัวอื่น ๆ ทั้งหมด ที่ตั้งไว้ก่อนหน้านี้ระหว่างการจัดการคำขอเดียวกัน ชื่อส่วนหัวเป็น ตัวพิมพ์ใหญ่ แต่ให้นามแฝงสำหรับชื่อส่วนหัวที่มีเส้นประเป็น ตัวพิมพ์เล็ก : {ContentType = "foo"}
เป็นรูปแบบทางเลือกสำหรับ {["Content-Type"] = "foo"}
body
เป็นสตริงเสริม
serveContent(name, parameters)
: แสดงเทมเพลตโดยใช้พารามิเตอร์ที่ให้ไว้ name
คือสตริงที่ตั้งชื่อเทมเพลต (ตามที่ตั้งค่าโดยการเรียกใช้ setTemplate
) และ parameters
คือตารางที่มีพารามิเตอร์เทมเพลตที่เก็บไว้เป็นคู่ชื่อ/ค่า (อ้างอิงเป็นตัวแปรในเทมเพลต)
run([options])
: เรียกใช้เซิร์ฟเวอร์โดยใช้เส้นทางที่กำหนดค่า โดยค่าเริ่มต้นเซิร์ฟเวอร์จะฟังบน localhost และพอร์ต 8080 ค่าเหล่านี้สามารถเปลี่ยนแปลงได้โดยการตั้ง addr
และค่า port
ในตาราง options
ตัวอย่างที่เรียกใช้ต้องรวมถึงคำสั่ง require
ในไฟล์ .init.lua
ซึ่งโหลดโมดูลด้วยรหัสตัวอย่างแต่ละตัวดังนั้นสำหรับตัวอย่างโชว์เคสที่ใช้ใน showcase.lua
, .init.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`
ตัวอย่างการแสดงแสดงให้เห็นถึงคุณสมบัติ Fullmoon หลายประการ:
serveAsset
)serveRedirect
)ต้องเพิ่มไฟล์ต่อไปนี้ใน RedBean Executable/Archive:
.init.lua - ต้องการ "Showcase" .lua/fullmoon.lua .lua/showcase.lua
ตัวอย่าง TechEmpower ใช้ประเภทการทดสอบที่หลากหลายสำหรับมาตรฐานเว็บเฟรมเวิร์กโดยใช้ FullMoon และฐานข้อมูล SQLite ในหน่วยความจำ
ตัวอย่างนี้แสดงให้เห็นถึงคุณสมบัติ Fullmoon/Redbean หลายประการ:
ต้องเพิ่มไฟล์ต่อไปนี้ใน RedBean Executable/Archive:
.init.lua - ต้องการ "Techbench" .lua/fullmoon.lua .lua/techbench.lua
ตัวอย่างบอร์ด HTMX แสดงให้เห็นถึงแอปพลิเคชันง่าย ๆ ที่สร้างชิ้นส่วน HTML ที่ส่งไปยังไคลเอนต์โดยใช้ไลบรารี HTMX
ตัวอย่างนี้แสดงให้เห็นถึงคุณสมบัติ Fullmoon/Redbean หลายประการ:
ต้องเพิ่มไฟล์ต่อไปนี้ใน RedBean Executable/Archive:
.init.lua - ต้องการ "htmxboard" .lua/fullmoon.lua .lua/htmxboard.lua สินทรัพย์/styles.css tmpl/* - ไฟล์ทั้งหมดจากตัวอย่าง/htmxboard/tmpl ไดเรกทอรี
หมายเหตุ 1: เนื่องจากข้อมูลทั้งหมดถูกเก็บไว้ในหน่วยความจำ ตัวอย่างนี้จึงถูกดำเนินการในโหมด Uniprocess
หมายเหตุ 2: ตัวอย่างนี้จะดึง HTMX, Hyperscript และไลบรารีที่สามารถจัดเรียงได้จากทรัพยากรภายนอก แต่ห้องสมุดเหล่านี้สามารถเก็บไว้เป็นสินทรัพย์ในท้องถิ่นได้ดังนั้นจึงให้แพคเกจการกระจายแบบพกพาที่พกพาได้อย่างสมบูรณ์
ตัวอย่าง HTMX SSE แสดงวิธีสร้างเหตุการณ์เซิร์ฟเวอร์ (SSE) ที่สามารถสตรีมไปยังไคลเอนต์ (ซึ่งแสดงผลลัพธ์โดยใช้ไลบรารี HTMX และส่วนขยาย SSE)
ตัวอย่างนี้แสดงให้เห็นถึงคุณสมบัติ Fullmoon/Redbean หลายประการ:
streamContent
)ต้องเพิ่มไฟล์ต่อไปนี้ใน RedBean Executable/Archive:
.init.lua - ต้องการ "htmxsse" .lua/fullmoon.lua .lua/htmxsse.lua
แอปพลิเคชัน FullMoon แต่ละรายการจะติดตามการไหลพื้นฐานเดียวกันกับห้าองค์ประกอบหลัก:
ลองดูที่แต่ละส่วนประกอบเริ่มต้นจากการกำหนดเส้นทางคำขอ
Fullmoon จัดการคำขอ HTTP แต่ละครั้งโดยใช้กระบวนการเดียวกัน:
false
หรือ nil
การส่งคืนจากตัวจัดการการดำเนินการ (และดำเนินการต่อไปเป็นอย่างอื่น) โดยทั่วไปคำจำกัดความเส้นทางผูก URL คำขอ (และชุดของเงื่อนไข) กับตัวจัดการการดำเนินการ (ซึ่งเป็นฟังก์ชัน LUA ปกติ) เงื่อนไขทั้งหมดจะถูกตรวจสอบตามลำดับแบบสุ่มสำหรับแต่ละ URL ที่ตรงกับคำจำกัดความของเส้นทาง ทันทีที่เงื่อนไขใด ๆ ล้มเหลวการประมวลผลเส้นทางจะถูกยกเลิกและเส้นทางต่อไปจะถูกตรวจสอบ ด้วยข้อยกเว้นหนึ่งข้อ : เงื่อนไขใด ๆ สามารถตั้งค่า otherwise
ซึ่งกระตุ้นการตอบกลับด้วยรหัสสถานะที่ระบุ
หากไม่มีเส้นทางตรงกับคำขอการประมวลผล 404 เริ่มต้นจะถูกเรียกใช้ซึ่งสามารถปรับแต่งได้โดยการลงทะเบียนเทมเพลต 404 ที่กำหนดเอง ( fm.setTemplate("404", "My 404 page...")
)
แต่ละเส้นทางใช้เส้นทางที่ตรงกับเส้นทางดังนั้นเส้นทาง "/hello"
จะตรงกันสำหรับ /hello
และไม่ตรงกับ /hell
/hello-world
หรือ /hello/world
เส้นทางด้านล่างตอบกลับด้วย "สวัสดีโลก!" สำหรับคำขอทั้งหมดที่กำกับที่ /hello
Path และส่งคืน 404 สำหรับคำขออื่น ๆ ทั้งหมด
fm . setRoute ( " /hello " , function ( r ) return " Hello, World! " end )
เพื่อให้ตรงกับเส้นทางที่ /hello
เป็นเพียงส่วนหนึ่งของมันพารามิเตอร์เสริมและ splat สามารถใช้
นอกเหนือจากเส้นทางที่คงที่เส้นทางใด ๆ อาจรวมถึงตัวยึดตำแหน่งสำหรับพารามิเตอร์ซึ่งถูกระบุโดย A :
ตามด้วยชื่อพารามิเตอร์ทันที:
fm . setRoute ( " /hello/:name " ,
function ( r ) return " Hello, " .. ( r . params . name ) end )
แต่ละพารามิเตอร์ตรงกับอักขระหนึ่งตัวขึ้นไปยกเว้น /
ดังนั้นเส้นทาง "/hello/:name"
matches /hello/alice
, /hello/bob
, /hello/123
และไม่ตรงกับ /hello/bob/and/alice
(เนื่องจากจาก slashes ไปข้างหน้าที่ไม่จับคู่) หรือ /hello/
(เพราะความยาวของชิ้นส่วนที่จับคู่กับเป็นศูนย์)
ชื่อพารามิเตอร์สามารถรวมอักขระตัวอักษรและตัวเลขเท่านั้นและ _
พารามิเตอร์สามารถเข้าถึงได้โดยใช้ตารางคำขอและตาราง params
เช่น r.params.name
สามารถใช้เพื่อรับค่าของพารามิเตอร์ name
จากตัวอย่างก่อนหน้า
ส่วนหรือพารามิเตอร์เส้นทางที่ระบุใด ๆ สามารถประกาศเป็นตัวเลือกโดยการห่อเป็นวงเล็บ:
fm . setRoute ( " /hello(/:name) " ,
function ( r ) return " Hello, " .. ( r . params . name or " World! " ) end )
ในตัวอย่างข้างต้นทั้ง /hello
and /hello/Bob
ได้รับการยอมรับ แต่ไม่ใช่ /hello/
เนื่องจาก slash ต่อท้ายเป็นส่วนหนึ่งของส่วนเสริมและ :name
ยังคงคาดหวังหนึ่งตัวอักษรหรือมากกว่า
พารามิเตอร์ทางเลือกที่ไม่มีใครเทียบได้รับ false
เป็นค่าของมันดังนั้นในกรณีด้านบน "สวัสดีโลก!" ได้รับการส่งคืนสำหรับ URL คำขอ /hello
สามารถระบุพารามิเตอร์ทางเลือกมากกว่าหนึ่งตัวและชิ้นส่วนเสริมสามารถซ้อนกันได้ดังนั้นทั้ง "/posts(/:pid/comments(/:cid))"
และ "/posts(/:pid)/comments(/:cid)"
เป็นค่าเส้นทางที่ถูกต้อง
มีพารามิเตอร์ชนิดอื่นที่เรียกว่า Splat ที่เขียนเป็น *
และจับคู่อักขระเป็นศูนย์หรือมากกว่า รวมถึง Slash ไปข้างหน้า ( /
) Splat จะถูกเก็บไว้ในตาราง params
ภายใต้ชื่อ splat
ตัวอย่างเช่นเส้นทาง "/download/*"
ตรงกับ /download/my/file.zip
และ splat จะได้รับค่าของ my/file.zip
หากจำเป็นต้องใช้ splats หลายตัวในเส้นทางเดียวกัน SPLATS สามารถกำหนดชื่อได้คล้ายกับพารามิเตอร์อื่น ๆ : /download/*path/*fname.zip
(แม้ว่าผลลัพธ์เดียวกันสามารถทำได้โดยใช้ /download/*path/:fname.zip
ในขณะที่ Splat แรกจับชิ้นส่วนเส้นทางทั้งหมดยกเว้นชื่อไฟล์)
พารามิเตอร์ทั้งหมด (รวมถึง Splat) สามารถปรากฏในส่วนใดส่วนหนึ่งของเส้นทางและสามารถล้อมรอบด้วยข้อความอื่น ๆ ซึ่งจำเป็นต้องจับคู่กันอย่างแน่นอน ซึ่งหมายความว่าเส้นทาง "/download/*/:name.:ext"
ตรงกับ /download/my/path/file.zip
และ params.name
ได้รับ file
params.ext
รับ zip
และ params.splat
ได้รับค่า my/path
อีกเหตุผลหนึ่งที่ใช้ Splat คือการอนุญาตให้มีเส้นทางหลายเส้นทางที่มีเส้นทางเดียวกันที่จะลงทะเบียนในระบบ การใช้งานปัจจุบันเขียนทับเส้นทางด้วยชื่อเดียวกันและเพื่อหลีกเลี่ยงว่าสามารถใช้ splat ที่มีชื่อเพื่อสร้างเส้นทางที่ไม่ซ้ำกัน ตัวอย่างเช่น,
fm . setRoute ( " /*dosomething1 " , function ( r ) return " something 1 " end )
fm . setRoute ( " /*dosomething2 " , function ( r ) return " something 2 " end )
สิ่งนี้สามารถใช้ในสถานการณ์เมื่อมีชุดของเงื่อนไขที่ต้องตรวจสอบในตัวจัดการแอ็คชั่นและในขณะที่มันอาจเป็นไปได้ที่จะรวมทั้งสองเส้นทางเข้าด้วยกันบางครั้งมันก็สะอาดกว่าที่จะแยกออกจากกัน
ค่าเริ่มต้นสำหรับพารามิเตอร์คืออักขระทั้งหมด (ยกเว้น /
) ที่มีความยาวหนึ่งรายการหรือมากกว่า ในการระบุชุดอักขระที่ถูกต้องที่แตกต่างกันสามารถเพิ่มได้ในตอนท้ายของชื่อตัวแปร ตัวอย่างเช่นการใช้ :id[%d]
แทน :id
เปลี่ยนพารามิเตอร์ให้ตรงกับตัวเลขเท่านั้น
fm . setRoute ( " /hello(/:id[%d]) " ,
function ( r ) return " Hello, " .. ( r . params . id or " World! " ) end )
สนับสนุนคลาสตัวละคร LUA ต่อไปนี้: %w
, %d
, %a
, %l
, %u
และ %x
; อักขระเครื่องหมายวรรคตอนใด ๆ (รวมถึง %
และ ]
) สามารถหลบหนีได้ด้วย %
ไม่รองรับ คลาสเชิงลบ (เขียนเป็น Lua as %W
) แต่รองรับไวยากรณ์ไม่ได้อยู่ในชุดดังนั้น [^%d]
ตรงกับพารามิเตอร์ที่ไม่รวมตัวเลขใด ๆ
โปรดทราบว่าจำนวนของการทำซ้ำไม่สามารถเปลี่ยนแปลงได้ (ดังนั้น :id[%d]*
ไม่ใช่วิธีที่ถูกต้องในการยอมรับตัวเลขศูนย์หรือมากกว่า-มากกว่า) เนื่องจากอนุญาตให้ใช้ชุดเท่านั้นและค่ายังคงยอมรับอักขระอย่างน้อยหนึ่งตัว หากต้องการความยืดหยุ่นในการอธิบายรูปแบบที่ยอมรับได้มากขึ้นคุณสามารถใช้ตัวตรวจสอบความถูกต้องแบบกำหนดเองเพื่อขยายตรรกะการจับคู่
พารามิเตอร์การสืบค้นและฟอร์มสามารถเข้าถึงได้ในลักษณะเดียวกับพารามิเตอร์พา ธ โดยใช้ตาราง params
ในตาราง request
ที่ส่งผ่านไปยังตัวจัดการการกระทำแต่ละตัว โปรดทราบว่าหากมีความขัดแย้งระหว่างพารามิเตอร์และชื่อแบบสอบถาม/รูปแบบ ชื่อพารามิเตอร์จะมีความสำคัญ
มีกรณีพิเศษหนึ่งกรณีที่อาจส่งผลให้ตารางที่ส่งคืนแทนค่าสตริง: หากชื่อพารามิเตอร์แบบสอบถาม/ฟอร์มสิ้นสุดใน []
ผลลัพธ์ที่ตรงกันทั้งหมด (หนึ่งรายการหรือมากกว่า) จะถูกส่งคืนเป็นตาราง ตัวอย่างเช่นสำหรับสตริงการสืบค้น a[]=10&a[]&a[]=12&a[]=
ค่าของ params["a[]"]
คือ {10, false, 12, ""}
เมื่อการเขียนชื่อพารามิเตอร์เหล่านี้อาจต้องใช้วงเล็บหลายตัว params.a
สามารถใช้เป็นทางลัดสำหรับ params["a[]"]
โดยทั้งสองรูปแบบกลับตารางเดียวกัน
พารามิเตอร์ Multipart จะถูกประมวลผลเมื่อมีการร้องขอและสามารถเข้าถึงได้ในลักษณะเดียวกับส่วนที่เหลือของพารามิเตอร์โดยใช้ตาราง params
ตัวอย่างเช่นพารามิเตอร์ที่มีชื่อ simple
และสามารถเรียกคืน more
จากข้อความที่มีประเภทเนื้อหา multipart/form-data
โดยใช้ params.simple
และ params.more
เนื่องจากเนื้อหาหลายส่วนอาจรวมถึงส่วนหัวและพารามิเตอร์เพิ่มเติมภายในส่วนหัวเหล่านั้นจึงสามารถเข้าถึงได้ด้วยฟิลด์ multipart
ของตาราง params
:
fm . setRoute ({ " /hello " , simple = " value " }, function ( r )
return " Show " .. r . params . simple .. " " .. r . params . multipart . more . data )
end )
ตาราง multipart
รวมถึงส่วนทั้งหมดของข้อความ Multipart (ดังนั้นจึงสามารถทำซ้ำได้มากกว่าการใช้ ipairs
) แต่ยังอนุญาตให้เข้าถึงชื่อพารามิเตอร์ ( params.multipart.more
) แต่ละองค์ประกอบยังเป็นตารางที่มีฟิลด์ต่อไปนี้:
nil
ถ้าไม่nil
ถ้าไม่ การประมวลผลแบบหลายส่วนนี้ใช้ประเภทย่อยหลายประเภทและจัดการกับข้อความหลายส่วนแบบเรียกซ้ำ นอกจากนี้ยังแทรกชิ้นส่วนที่มีค่า Content-ID
ที่ตรงกับพารามิเตอร์ start
ในตำแหน่งแรก
แม้จะมีตัวอย่างก่อนหน้านี้ทั้งหมดที่แสดงเส้นทางเดียว แต่ก็ไม่ค่อยเกิดขึ้นในแอปพลิเคชันจริง เมื่อมีหลายเส้นทางพวกเขาจะ ถูกประเมินตามลำดับที่ลงทะเบียน
การโทร setRoute
หนึ่งสายยังสามารถตั้งค่าหลายเส้นทางเมื่อพวกเขามีชุดเงื่อนไขเดียวกันและแบ่งปันตัวจัดการการกระทำเดียวกัน:
fm . setRoute ({ " /route1 " , " /route2 " }, handler )
สิ่งนี้เทียบเท่ากับการตั้งค่าการโทรสองครั้งแต่ละเส้นทาง:
fm . setRoute ( " /route1 " , handler )
fm . setRoute ( " /route2 " , handler )
เนื่องจากเส้นทางได้รับการประเมินตามลำดับที่ตั้งค่าเส้นทางที่เลือกได้มากขึ้นจะต้องตั้งค่าก่อนมิฉะนั้นพวกเขาอาจไม่ได้รับโอกาสที่จะได้รับการประเมิน:
fm . setRoute ( " /user/bob " , handlerBob )
fm . setRoute ( " /user/:name " , handlerName )
หากเส้นทางถูกตั้งค่าในลำดับตรงข้าม /user/bob
อาจไม่สามารถตรวจสอบได้ตราบใดที่ตัวจัดการการกระทำ "/user/:name"
ส่งคืนผลลัพธ์ที่ไม่ใช่ false
บางอย่าง
ตามที่อธิบายไว้ก่อนหน้านี้หากไม่มีเส้นทางที่ตรงกันการตอบกลับด้วยรหัสสถานะ 404 จะถูกส่งคืน อาจมีกรณีที่ ไม่ เป็นที่ต้องการ ตัวอย่างเช่นเมื่อแอปพลิเคชันรวมสคริปต์ Lua เพื่อจัดการคำขอที่ไม่ได้ลงทะเบียนอย่างชัดเจนเป็นเส้นทาง ในกรณีเหล่านั้นสามารถเพิ่มเส้นทางการจับทั้งหมดที่ใช้การประมวลผล RedBean เริ่มต้น (ชื่อของพารามิเตอร์ Splat นั้นใช้เพื่อทำให้เส้นทางนี้เป็นไปตามเส้นทางนี้กับเส้นทางอื่น /*
ที่อาจใช้ในที่อื่น):
fm . setRoute ( " /*catchall " , fm . servePath )
แต่ละเส้นทางสามารถให้ชื่อเสริมซึ่งมีประโยชน์ในการอ้างอิงเส้นทางนั้นเมื่อต้องสร้าง URL ตามค่าพารามิเตอร์ที่เฉพาะเจาะจง ให้ฟังก์ชั่น makePath
ยอมรับชื่อเส้นทางหรือ URL เส้นทางเองรวมถึงตารางพารามิเตอร์และส่งคืนเส้นทางที่มีตัวยึดพารามิเตอร์ที่มีประชากร:
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
หากสองเส้นทางใช้ชื่อเดียวกันชื่อนั้นจะเชื่อมโยงกับเส้นทางที่ลงทะเบียนล่าสุด แต่ทั้งสองเส้นทางยังคงอยู่
ชื่อเส้นทางยังสามารถใช้กับเส้นทางภายนอก/คงที่ที่ใช้สำหรับการสร้าง URL เท่านั้น
หากเส้นทางใช้สำหรับการสร้างเส้นทางเท่านั้นมันไม่จำเป็นต้องมีตัวจัดการเส้นทาง:
fm . setRoute ({ " https://youtu.be/:videoid " , routeName = " youtube " })
fm . makePath ( " youtube " , { videoid = " abc " }) -- > https://youtu.be/abc
เส้นทางที่ไม่มีตัวจัดการแอ็คชั่นใด ๆ ถูกข้ามระหว่างกระบวนการจับคู่เส้นทาง
เส้นทางภายในอนุญาตให้เปลี่ยนเส้นทางของ URL หนึ่งชุดไปยังเส้นทางอื่น URL เป้าหมายสามารถชี้ไปที่ทรัพยากรคงที่หรือสคริปต์ .lua
ตัวอย่างเช่นหากคำขอสำหรับสถานที่หนึ่งจะต้องเปลี่ยนเส้นทางไปยังที่อื่นการกำหนดค่าการกำหนดค่าต่อไปนี้จะเปลี่ยนคำขอสำหรับทรัพยากรใด ๆ ภายใต้ /blog/
URL ไปยังผู้ที่อยู่ภายใต้ /new-blog/
URL ตราบใดที่ทรัพยากรเป้าหมายมีอยู่:
fm . setRoute ( " /blog/* " , " /new-blog/* " )
เส้นทางนี้ยอมรับคำขอ /blog/post1
และให้บริการ /new-blog/post1
เป็นการตอบสนองตราบใดที่มีสินทรัพย์ /new-blog/post1
อยู่ หากสินทรัพย์ไม่มีอยู่จะมีการตรวจสอบเส้นทางต่อไป ในทำนองเดียวกันการใช้ fm.setRoute("/static/*", "/*")
ทำให้เกิดการร้องขอสำหรับ /static/help.txt
ที่จะให้บริการทรัพยากร /help.txt
URL ทั้งสองสามารถรวมพารามิเตอร์ที่กรอกหากได้รับการแก้ไข:
fm . setRoute ( " /blog/:file " , " /new-blog/:file.html " ) -- <<-- serve "nice" URLs
fm . setRoute ( " /new-blog/:file.html " , fm . serveAsset ) -- <<-- serve original URLs
ตัวอย่างนี้แก้ไข URL "ดี" ที่ให้บริการเวอร์ชัน "HTML" ของพวกเขา โปรดทราบว่าสิ่งนี้ ไม่ได้ทริกเกอร์การเปลี่ยนเส้นทางฝั่งไคลเอ็นต์โดยการคืนรหัสสถานะ 3xx
แต่แทนที่จะจัดการเส้นทางใหม่ภายใน นอกจากนี้โปรดทราบว่า กฎข้อที่สองนั้นจำเป็นต้องใช้ URL "ดั้งเดิม" เนื่องจากไม่ได้รับการจัดการโดยกฎข้อแรกเพราะหากคำขอสำหรับ /blog/mylink.html
แล้ว URL ที่เปลี่ยนเส้นทางคือ /new-blog/mylink.html.html
ซึ่งไม่น่าจะมีอยู่ดังนั้นเส้นทางจึงถูกข้ามและตรวจสอบเส้นทางถัดไป หากจำเป็นต้องใช้การจัดการของตัวคั่นพา ธ เช่นกัน * สามารถใช้ *path
แทน :file
ตามที่ *
อนุญาตให้แยกพา ธ
หากแอปพลิเคชันจำเป็นต้องดำเนินการฟังก์ชั่นที่แตกต่างกันขึ้นอยู่กับค่าเฉพาะของแอตทริบิวต์คำขอ (ตัวอย่างเช่นวิธีการ) ไลบรารีนี้มีสองตัวเลือกหลัก: (1) ตรวจสอบค่าแอตทริบิวต์ตัวจัดการการกระทำ (เช่นโดยใช้ request.method == "GET"
ตรวจสอบ) และ (2) เพิ่มเงื่อนไขที่กรองการร้องขอออกมาซึ่งเฉพาะคำขอโดยใช้ค่าแอตทริบิวต์ที่ระบุถึงตัวจัดการการกระทำ ส่วนนี้อธิบายตัวเลือกที่สองในรายละเอียดเพิ่มเติม
แต่ละเส้นทางที่ลงทะเบียนโดยค่าเริ่มต้นจะตอบกลับวิธี HTTP ทั้งหมด (รับ, ใส่, โพสต์, ฯลฯ ) แต่เป็นไปได้ที่จะกำหนดค่าแต่ละเส้นทางเพื่อตอบสนองต่อวิธี HTTP เฉพาะเท่านั้น:
fm . setRoute ( fm . GET " /hello(/:name) " ,
function ( r ) return " Hello, " .. ( r . params . name or " World! " ) end )
ในกรณีนี้ไวยากรณ์ fm.GET"/hello(/:name)"
กำหนดค่าเส้นทางที่จะยอมรับการ GET
เท่านั้น ไวยากรณ์นี้เทียบเท่ากับการผ่านตารางด้วยเส้นทางและเงื่อนไขการกรองเพิ่มเติมใด ๆ :
fm . setRoute ({ " /hello(/:name) " , method = " GET " },
function ( r ) return " Hello, " .. ( r . params . name or " World! " ) end )
หากจำเป็นต้องระบุวิธีการมากกว่าหนึ่งวิธีตารางที่มีรายการวิธีการสามารถส่งผ่านแทนค่าสตริงเดียว:
fm . setRoute ({ " /hello(/:name) " , method = { " GET " , " POST " }},
function ( r ) return " Hello, " .. ( r . params . name or " World! " ) end )
ทุกเส้นทางที่อนุญาตให้รับคำขอ GET
(โดยปริยาย) อนุญาตให้มีการร้องขอ HEAD
และคำขอนั้นได้รับการจัดการโดยการส่งคืนส่วนหัวทั้งหมดโดยไม่ส่งตัวเอง หากด้วยเหตุผลบางอย่างการจัดการโดยนัยนี้ไม่เป็นที่ต้องการให้เพิ่ม HEAD = false
ลงในตารางวิธีการปิดใช้งาน (เช่นใน method = {"GET", "POST", HEAD = false}
)
โปรดทราบว่าคำขอด้วยวิธีการไม่จับคู่จะไม่ถูกปฏิเสธ แต่จะต้องผ่านการตรวจสอบโดยเส้นทางอื่น ๆ และทริกเกอร์รหัสสถานะ 404 ที่ส่งคืนหากพวกเขาไม่ได้รับการจับคู่ (ยกเว้นหนึ่งข้อ)
นอกเหนือจาก method
ยังสามารถใช้เงื่อนไขอื่น ๆ ได้โดยใช้ host
, clientAddr
, serverAddr
, scheme
, ส่วนหัวคำขอและพารามิเตอร์ ตัวอย่างเช่นการระบุ name = "Bob"
เป็นหนึ่งในเงื่อนไขทำให้มั่นใจได้ว่าค่าของพารามิเตอร์ name
จะเป็น "บ๊อบ" สำหรับตัวจัดการการกระทำที่จะเรียก
ส่วนหัวคำขอใด ๆ สามารถตรวจสอบได้โดยใช้ชื่อส่วนหัวเป็นคีย์ดังนั้น ContentType = "multipart/form-data"
จะเป็นที่พอใจหากค่าของส่วนหัว Content-Type
เป็น multipart/form-data
โปรดทราบว่าค่าส่วนหัวอาจรวมถึงองค์ประกอบอื่น ๆ (ขอบเขตหรือชุดตัวอักษรเป็นส่วนหนึ่งของค่า Content-Type
) และเปรียบเทียบเฉพาะประเภทสื่อจริงเท่านั้น
เนื่องจากชื่อสำหรับส่วนหัวพารามิเตอร์และคุณสมบัติสามารถทับซ้อนกันได้จึงถูกตรวจสอบในลำดับต่อไปนี้:
ContentType
method
port
host
ฯลฯ ) และ ส่วนหัว Host
จะถูกตรวจสอบก่อน (แม้จะเป็นคำเดียว) ดังนั้นการอ้างอิงตัวกรอง Host
ตาม Host
ส่วนหัวในขณะที่อ้างอิงตัวกรอง host
ตาม host
คุณสมบัติ
ค่าสตริงไม่ใช่ค่าเดียวที่สามารถใช้ในเส้นทางที่มีเงื่อนไข หากมีมากกว่าหนึ่งค่าที่ยอมรับได้การผ่านตารางอนุญาตให้แสดงรายการของค่าที่ยอมรับได้ ตัวอย่างเช่นถ้า Bob
และ Alice
เป็นค่าที่ยอมรับได้แล้ว name = {Bob = true, Alice = true}
เป็นการแสดงออกว่านี่เป็นเงื่อนไข
ค่าพิเศษสองค่าที่ส่งผ่านในตารางอนุญาตให้ใช้ regex หรือการตรวจสอบ รูปแบบ :
regex
: ยอมรับสตริงที่มีนิพจน์ทั่วไป ตัวอย่างเช่น name = {regex = "^(Bob|Alice)$"}
มีผลลัพธ์เช่นเดียวกับการตรวจสอบแฮชที่แสดงก่อนหน้านี้ในส่วนนี้pattern
: ยอมรับสตริงที่มีการแสดงออกของรูปแบบ LUA ตัวอย่างเช่น name = {pattern = "^%u%l+$"}
ยอมรับค่าที่เริ่มต้นด้วยอักขระตัวพิมพ์ใหญ่ตามด้วยอักขระตัวพิมพ์เล็กหนึ่งตัวหรือมากกว่า การตรวจสอบทั้งสองนี้สามารถรวมกับการตรวจสอบการดำรงอยู่ของตาราง: name = {Bob = true, regex = "^Alice$"}
ยอมรับทั้งค่า Bob
และ Alice
หากการตรวจสอบการมีอยู่ของตารางแรกล้มเหลวผลลัพธ์ของการนิพจน์ regex
หรือ pattern
จะถูกส่งคืน
ประเภทสุดท้ายของตัวตรวจสอบที่กำหนดเองคือฟังก์ชั่น ฟังก์ชั่นที่ได้รับจะได้รับค่าเพื่อตรวจสอบและผลลัพธ์จะถูกประเมินว่าเป็น false
หรือ true
ตัวอย่างเช่นการผ่าน id = tonumber
ทำให้มั่นใจได้ว่าค่า id
เป็นตัวเลข เป็นอีกตัวอย่างหนึ่ง clientAddr = fm.isLoopbackIp
ทำให้มั่นใจได้ว่าที่อยู่ไคลเอนต์เป็นที่อยู่ IP แบบวนรอบ
fm . setRoute ({ " /local-only " , clientAddr = fm . isLoopbackIp },
function ( r ) return " Local content " end )
เนื่องจากฟังก์ชั่นการตรวจสอบความถูกต้องสามารถสร้างได้แบบไดนามิกสิ่งนี้ใช้งานได้เช่นกัน:
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 )
เป็นสิ่งสำคัญที่ต้องจำไว้ว่าฟังก์ชั่นการตรวจสอบความถูกต้องจะส่งคืนฟังก์ชั่นที่เรียกว่าในระหว่างการร้องขอเพื่อใช้การตรวจสอบ ในตัวอย่างก่อนหน้าฟังก์ชั่นที่ส่งคืนยอมรับค่าส่วนหัวและเปรียบเทียบกับขีด จำกัด ที่ผ่านระหว่างการสร้าง
ในบางกรณีความล้มเหลวในการตอบสนองเงื่อนไขเป็นเหตุผลที่เพียงพอที่จะส่งคืนการตอบกลับบางอย่างกลับไปยังลูกค้าโดยไม่ตรวจสอบเส้นทางอื่น ในกรณีเช่นนี้การตั้งค่า otherwise
ค่าเป็นตัวเลขหรือฟังก์ชั่นส่งคืนการตอบสนองด้วยสถานะที่ระบุหรือผลลัพธ์ของฟังก์ชัน:
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 )
ในตัวอย่างนี้เอ็นจิ้นการกำหนดเส้นทางตรงกับเส้นทางจากนั้นตรวจสอบทั้งสองเงื่อนไขเปรียบเทียบค่าวิธีการกับ POST
และค่าของส่วนหัว Content-Length
กับผลลัพธ์ของฟังก์ชัน isLessThan
หาก หนึ่งในเงื่อนไข ไม่ตรงกันรหัสสถานะที่ระบุโดยค่า otherwise
จะถูกส่งคืนพร้อมกับการตอบกลับที่เหลือ
หากเงื่อนไข otherwise
ต้องใช้กับการตรวจสอบ ContentLength
เท่านั้น ค่า otherwise
พร้อมกับฟังก์ชันการตรวจสอบความถูกต้องสามารถย้ายไปยังตารางที่เกี่ยวข้องกับการตรวจสอบ ContentLength
:
fm . setRoute ( fm . POST { " /upload " ,
ContentLength = { isLessThan ( 100000 ), otherwise = 413 }
}, function ( r ) ... handle the upload ... end )
ความแตกต่างระหว่างสองตัวอย่างสุดท้ายคือในตัวอย่างนี้เฉพาะความล้มเหลวในการตรวจสอบ ContentLength
ทำให้เกิดการตอบสนอง 413 (และวิธีอื่น ๆ ทั้งหมดจะผ่านไปยังเส้นทางอื่น ๆ ) ในขณะที่ในวิธีการก่อนหน้านี้ทั้ง method
และการตรวจสอบ ContentLength
ทำให้เกิดการตอบสนอง 413 เดียวกัน
โปรดทราบว่าเมื่อค่าที่ตรวจสอบเป็น nil
การตรวจสอบกับตารางจะถือว่าถูกต้องและยอมรับเส้นทาง ตัวอย่างเช่นการตรวจสอบพารามิเตอร์ทางเลือกที่ทำกับสตริง ( name = "Bo"
) ล้มเหลวหากค่าของ params.name
เป็น nil
แต่ผ่านหากตรวจสอบเดียวกันกับตาราง ( name = {Bo=true, Mo=true}
) รวมถึงการตรวจสอบ regex/รูปแบบ หากสิ่งนี้ไม่เป็นที่ต้องการฟังก์ชั่นการตรวจสอบความถูกต้องที่กำหนดเองสามารถตรวจสอบค่าที่คาดหวังได้อย่างชัดเจน
พิจารณาตัวอย่างต่อไปนี้:
fm . setRoute ({ " /hello(/:name) " ,
method = { " GET " , " POST " , otherwise = 405 }},
function ( r ) return " Hello, " .. ( r . params . name or " World! " ) end )
ในกรณีนี้หากจุดสิ้นสุดนี้เข้าถึงด้วยวิธี PUT
แทนที่จะตรวจสอบเส้นทางอื่น (เนื่องจากเงื่อนไข method
ไม่พอใจ) รหัสสถานะ 405 จะถูกส่งคืนตามที่กำหนดค่าด้วยค่าที่ระบุไว้ otherwise
ตามที่บันทึกไว้ในที่อื่นเส้นทางนี้ยอมรับคำขอ HEAD
ด้วย (แม้ว่าจะไม่อยู่ในรายการ) ตามคำ GET
เมื่อรหัสสถานะ 405 (วิธีการที่ไม่ดี) ถูกส่งคืนและไม่ได้ตั้งค่าส่วนหัว Allow
จะถูกตั้งค่าเป็นรายการวิธีการที่อนุญาตโดยเส้นทาง ในกรณีข้างต้นมีการตั้งค่าให้ GET, POST, HEAD, OPTIONS
เนื่องจากเป็นวิธีการที่อนุญาตโดยการกำหนดค่านี้ หากค่า otherwise
เป็นฟังก์ชัน (แทนที่จะเป็นตัวเลข) จากนั้นการส่งคืนผลลัพธ์ที่เหมาะสมและการตั้งค่าส่วนหัว Allow
เป็นความรับผิดชอบของฟังก์ชั่นนี้
ค่า otherwise
สามารถตั้งค่าเป็นฟังก์ชั่นซึ่งให้ความยืดหยุ่นมากกว่าการตั้งค่ารหัสสถานะ ตัวอย่างเช่นการตั้งค่า otherwise = fm.serveResponse(413, "Payload Too Large")
กระตุ้นการตอบกลับด้วยรหัสสถานะและข้อความที่ระบุ
การตรวจสอบแบบฟอร์มการจัดการมักจะต้องระบุชุดเงื่อนไขสำหรับพารามิเตอร์เดียวกันและข้อความแสดงข้อผิดพลาด makeValidator
กำหนดเองซึ่งอาจต้องส่งคืนเมื่อเงื่อนไขไม่เป็นที่พอใจ
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 )
ในตัวอย่างนี้ตัวตรวจสอบได้รับการกำหนดค่าให้ตรวจสอบพารามิเตอร์สองพารามิเตอร์ - "ชื่อ" และ "รหัสผ่าน" - สำหรับความยาวขั้นต่ำและสูงสุดของพวกเขาและส่งคืนข้อความเมื่อพารามิเตอร์ตัวใดตัวหนึ่งล้มเหลวในการตรวจสอบ
เนื่องจากการตรวจสอบที่ล้มเหลวทำให้เส้นทางถูกข้ามไปการให้ค่า otherwise
อนุญาตให้เกิดข้อผิดพลาดเป็นส่วนหนึ่งของการตอบกลับ:
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 ,
}
ในกรณีนี้ตัวจัดการ otherwise
จะได้รับข้อความแสดงข้อผิดพลาด (หรือตารางที่มีข้อความหากร้องขอโดยผ่านตัวเลือก all
ที่ครอบคลุมด้านล่าง) ซึ่งสามารถให้เป็นพารามิเตอร์เทมเพลตและส่งกลับไปยังไคลเอนต์
อีกทางเลือกหนึ่งคือเรียกใช้ฟังก์ชันการตรวจสอบโดยตรงในตัวจัดการการกระทำและส่งคืนผลลัพธ์:
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 )
ในตัวอย่างนี้ตัวตรวจสอบจะเรียกโดยตรงและผ่านตาราง ( r.params
) ด้วยค่าพารามิเตอร์ทั้งหมดเพื่อให้ฟังก์ชันการตรวจสอบความถูกต้องตรวจสอบค่ากับกฎที่ระบุ
ฟังก์ชั่นการตรวจสอบ true
จะส่งคืนความสำเร็จของสัญญาณหรือ nil, error
ในการส่งสัญญาณความล้มเหลวในการตรวจสอบกฎข้อใดข้อหนึ่ง สิ่งนี้จะช่วยให้การเรียกตัวตรวจสอบความถูกต้องถูกห่อไว้ใน assert
หากสคริปต์จำเป็นต้องส่งคืนข้อผิดพลาดทันที:
assert ( validator ( r . params )) -- throw an error if validation fails
return fm . serveRedirect ( 307 , " / " ) -- return redirect in other cases
มีการตรวจสอบการตรวจสอบต่อไปนี้:
minlen
: (จำนวนเต็ม) ตรวจสอบความยาวน้อยที่สุดของสตริงmaxlen
: (จำนวนเต็ม) ตรวจสอบความยาวสูงสุดของสตริงtest
: (ฟังก์ชั่น) เรียกฟังก์ชั่นที่ผ่านพารามิเตอร์หนึ่งพารามิเตอร์และคาดว่าจะส่งคืน true
หรือ nil | false [, error]
oneof
: ( value | { table of values to be compared against }
) ตรวจสอบว่าพารามิเตอร์ตรงกับค่าหนึ่งในค่าที่ให้ไว้หรือไม่pattern
: (สตริง) ตรวจสอบว่าพารามิเตอร์ตรงกับนิพจน์รูปแบบ LUA หรือไม่นอกเหนือจากการตรวจสอบกฎอาจมีตัวเลือก:
optional
: (บูล) ทำให้พารามิเตอร์เป็นตัวเลือกเมื่อ nil
พารามิเตอร์ทั้งหมดจะต้องใช้โดยค่าเริ่มต้นดังนั้นตัวเลือกนี้จะอนุญาตให้กฎถูกข้ามเมื่อไม่มีการจัดเตรียมพารามิเตอร์ กฎทั้งหมดจะยังคงใช้หากพารามิเตอร์ไม่ได้ไม่มีmsg
: (String) เพิ่มข้อความลูกค้าสำหรับสิ่งนี้หากการตรวจสอบใดรายการหนึ่งล้มเหลวซึ่งเขียนทับข้อความจากการตรวจสอบแต่ละรายการ ข้อความอาจรวมถึงตัวยึดตำแหน่ง ( %s
) ซึ่งจะถูกแทนที่ด้วยชื่อพารามิเตอร์The validator itself also accepts several options that modify how the generated errors are returned or handled:
otherwise
: (function) sets an error handler that is called when one of the checks fails. The function receives the error(s) triggered by the checks.all
: (bool) configures the validator to return all errors instead of just the first one. By default only one (first) error is returned as a string, so if all errors are requested, they are returned as a table with each error being a separate item.key
: (bool) configures the validator to return error(s) as values in a hash table (instead of element) where the keys are parameter names. This is useful to pass the table with errors to a template that can then display errors.name
and errors.password
error messages next to their input fields. An action handler receives all incoming HTTP requests filtered for a particular route. Each of the examples shown so far includes an action handler, which is passed as a second parameter to the setRoute
method.
Multiple action handlers can be executed in the course of handling one request and as soon as one handler returns a result that is evaluated as a non- false
value, the route handling process ends. Returning false
or nil
from an action handler continues the processing, which allows implementing some common processing that applies to multiple routes (similar to what is done using "before" filters in other frameworks):
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 )
In this example, the first route can generate three outcomes:
method
check) is not matched, then the 405 status code is returned.false
, which continues processing with other routes, or fails to retrieve the user and returns an error.In general, an action handler can return any of the following values:
true
: this stops any further processing, sets the headers that have been specified so far, and returns the generated or set response body.false
or nil
: this stops the processing of the current route and proceeds to the next one.Content-Type
is set based on the body content (using a primitive heuristic) if not set explicitly.serve*
methods): this executes the requested method and returns an empty string or true
to signal the end of the processing.true
is returned (and a warning is logged). Normally any processing that results in a Lua error is returned to the client as a server error response (with the 500 status code). To assist with local debugging, the error message includes a stack trace, but only if the request is sent from a loopback or private IP (or if redbean is launched with the -E
command line option).
It may be desirable to return a specific response through multiple layers of function calls, in which case the error may be triggered with a function value instead of a string value. For example, executing error(fm.serve404)
results in returning the 404 status code, which is similar to using return fm.serve404
, but can be executed in a function called from an action handler (and only from inside an action handler).
Here is a more complex example that returns the 404 status code if no record is fetched (assuming there is a table test
with a field id
):
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)
This example uses the serve404
function, but any other serve* method can also be used.
Each action handler accepts a request table that includes the following attributes:
method
: request HTTP method (GET, POST, and others).host
: request host (if provided) or the bind address.serverAddr
: address to which listening server socket is bound.remoteAddr
: client ip4 address encoded as a number. This takes into consideration reverse proxy scenarios. Use formatIp
function to convert to a string representing the address.scheme
: request URL scheme (if any).path
: request URL path that is guaranteed to begin with /
.authority
: request URL with scheme, host, and port present.url
: request URL as an ASCII string with illegal characters percent encoded.body
: request message body (if present) or an empty string.date
: request date as a Unix timestamp.time
: current time as a Unix timestamp with 0.0001s precision.The request table also has several utility functions, as well as headers, cookies, and session tables that allow retrieving request headers, cookies, and session and setting of headers and cookies that are included with the response.
The same request table is given as a parameter to all (matched) action handlers, so it can be used as a mechanism to pass values between those action handlers, as any value assigned as a field in one handler is available in all other action handlers .
The headers
table provides access to the request headers. For example, r.headers["Content-Type"]
returns the value of the Content-Type
header. This form of header access is case-insensitive. A shorter form is also available ( r.headers.ContentType
), but only for registered headers and is case-sensitive with the capitalization preserved.
The request headers can also be set using the same syntax. For example, r.headers.MyHeader = "value"
sets MyHeader: value
response header. As the headers are set at the end of the action handler processing, headers set earlier can also be removed by assigning a nil
value.
Repeatable headers can also be assigned with values separated by commas: r.headers.Allow = "GET, POST"
.
The cookies
table provides access to the request cookies. For example, r.cookies.token
returns the value of the token
cookie.
The cookies can also be set using the same syntax. For example, r.cookies.token = "new value"
sets token
cookie to new value
. If the cookie needs to have its attributes set as well, then the value and the attributes need to be passed as a table: r.cookies.token = {"new value", secure = true, httponly = true}
.
The following cookie attributes are supported:
expires
: sets the maximum lifetime of the cookie as an HTTP-date timestamp. Can be specified as a date in the RFC1123 (string) format or as a UNIX timestamp (number of seconds).maxage
: sets number of seconds until the cookie expires. A zero or negative number expires the cookie immediately. If both expires
and maxage
are set, maxage
has precedence.domain
: sets the host to which the cookie is going to be sent.path
: sets the path that must be present in the request URL, or the client is not going to send the Cookie header.secure
: (bool) requests the cookie to be only send to the server when a request is made with the https: scheme.httponly
: (bool) forbids JavaScript from accessing the cookie.samesite
: ( Strict
, Lax
, or None
) controls whether a cookie is sent with cross-origin requests, providing some protection against cross-site request forgery attacks. Note that httponly
and samesite="Strict"
are set by default; a different set of defaults can be provided using cookieOptions
passed to the run method. Any attributes set with a table overwrite the default , so if Secure
needs to be enabled, make sure to also pass httponly
and samesite
options.
To delete a cookie, set its value to false
: for example, r.cookies.token = false
deletes the value of the token
cookie.
The session
table provides access to the session table that can be used to set or retrieve session values. For example, r.session.counter
returns the counter
value set previously. The session values can also be set using the same syntax. For example, r.session.counter = 2
sets the counter
value to 2
.
The session allows storing of nested values and other Lua values. If the session needs to be removed, it can be set to an empty table or a nil
value. Each session is signed with an application secret, which is assigned a random string by default and can be changed by setting session options.
The following functions are available as both request functions (as fields in the request table) and as library functions:
makePath(route[, parameters])
: creates a path from either a route name or a path string by populating its parameters using values from the parameters table (when provided). The path doesn't need to be just a path component of a URL and can be a full URL as well. Optional parts are removed if they include parameters that are not provided.makeUrl([url,] options)
: creates a URL using the provided value and a set of URL parameters provided in the options
table: scheme, user, pass, host, port, path, and fragment. The url
parameter is optional; the current request URL is used if url
is not specified. Any of the options can be provided or removed (using false
as the value). For example, makeUrl({scheme="https"})
sets the scheme for the current URL to https
.escapeHtml(string)
: escapes HTML entities ( &><"'
) by replacing them with their HTML entity counterparts ( &><"'
).escapePath(path)
: applies URL encoding ( %XX
) escaping path unsafe characters (anything other than -.~_@:!$&'()*+,;=0-9A-Za-z/
).formatHttpDateTime(seconds)
: converts UNIX timestamp (in seconds) to an RFC1123 string ( Mon, 21 Feb 2022 15:37:13 GMT
).Templates provide a simple and convenient way to return a predefined and parametrized content instead of generating it piece by piece.
The included template engine supports mixing an arbitrary text with Lua statements/expressions wrapped into {% %}
tags. All the code in templates uses a regular Lua syntax, so there is no new syntax to learn. There are three ways to include some Lua code:
{% statement %}
: used for Lua statements . For example, {% if true then %}Hello{% end %}
renders Hello
.{%& expression %}
: used for Lua expressions rendered as HTML-safe text. For example, {%& '2 & 2' %}
renders 2 & 2
.{%= expression %}
: used for Lua expressions rendered as-is (without escaping). For example, {%= 2 + 2 %}
renders 4
. Be careful, as HTML is not escaped with {%= }
, this should be used carefully due to the potential for XSS attacks.The template engine provides two main functions to use with templates:
setTemplate(name, text[, parameters])
: registers a template with the provided name and text (and uses parameters
as its default parameters). There are special cases where name
or text
parameters may not be strings, with some of those cases covered in the Loading templates section. parameters
is a table with template parameters as name/value pairs (referenced as variables in the template).render(name, parameters)
: renders a registered template using the parameters
table to set values in the template (with key/value in the table assigned to name/value in the template).There is only one template with a given name, so registering a template with an existing name replaces this previously registered template. This is probably rarely needed, but can be used to overwrite default templates.
Here is an example that renders Hello, World!
to the output buffer:
fm . setTemplate ( " hello " , " Hello, {%& title %}! " )
fm . render ( " hello " , { title = " World " })
Rendering statements using the expression syntax or expressions using the statement syntax is a syntax error that is reported when the template is registered. Function calls can be used with either syntax.
Any template error (syntax or run-time) includes a template name and a line number within the template. For example, calling fm.setTemplate("hello", "Hello, {%& if title then end %}!")
results in throwing hello:1: unexpected symbol near 'if'
error (as it inserts a Lua statement using the expression syntax).
Templates can also be loaded from a file or a directory using the same setTemplate
function, which is described later in the Loading templates section.
There are several aspects worth noting, as they may differ from how templates are processed in other frameworks:
json
and sse
templates are implemented using this approach.Each template accepts parameters that then can be used in its rendering logic. Parameters can be passed in two ways: (1) when the template is registered and (2) when the template is rendered. Passing parameters during registration allows to set default values that are used if no parameter is provided during rendering. ตัวอย่างเช่น,
fm . setTemplate ( " hello " , " Hello, {%& title %}! " , { title = " World " })
fm . render ( " hello " ) -- renders `Hello, World!`
fm . render ( " hello " , { title = " All " }) -- renders `Hello, All!`
nil
or false
values are rendered as empty strings without throwing any error, but any operation on a nil
value is likely to result in a Lua error. For example, doing {%& title .. '!' %}
(without title
set) results in attempt to concatenate a nil value (global 'title')
error.
There is no constraint on what values can be passed to a template, so any Lua value can be passed and then used inside a template.
In addition to the values that can be passed to templates, there are two special tables that provide access to cross-template values :
vars
: provides access to values registered with setTemplateVar
, andblock
: provides access to template fragments that can be overwritten by other templates. Any value registered with setTemplateVar
becomes accessible from any template through the vars
table. In the following example, the vars.title
value is set by the earlier setTemplateVar('title', 'World')
call:
fm . setTemplateVar ( ' title ' , ' World ' )
fm . setTemplate ( " hello " , " Hello, {%& vars.title %}! " )
fm . render ( " hello " ) -- renders `Hello, World!`
While undefined values are rendered as empty string by default (which may be convenient in most cases), there are still situations when it is preferrable to not allow undefined values to be silently handled. In this a special template variable ( if-nil
) can be set to handle those cases to throw an error or to log a message. For example, the following code throws an error, as the missing
value is undefined, which triggers if-nil
handler:
fm . setTemplateVar ( ' if-nil ' , function () error " missing value " end )
fm . setTemplate ( " hello " , " Hello, {%& vars.missing %}! " )
fm . render ( " hello " ) -- throws "missing value" error
Templates can be also rendered from other templates by using the render
function, which is available in every template:
fm . setTemplate ( " hello " , " Hello, {%& title %}! " )
fm . setTemplate ( " header " , " <h1>{% render('hello', {title = title}) %}</h1> " )
---- -----------------------------└──────────────────────────────┘----------
fm . render ( " header " , { title = ' World ' }) -- renders `<h1>Hello, World!</h1>`
There are no limits on how templates can be rendered from other templates, but no checks for loops are made either, so having circular references in template rendering (when a template A renders a template B, which in turn renders A again) is going to cause a Lua error.
It's worth noting that the render
function doesn't return the value of the template it renders, but instead puts it directly into the output buffer.
This ability to render templates from other templates allows producing layouts of any complexity. There are two ways to go about it:
To dynamically choose the template to use at render time, the template name itself can be passed as a parameter:
fm . setTemplate ( " hello " , " Hello, {%& title %}! " )
fm . setTemplate ( " bye " , " Bye, {%& title %}! " )
fm . setTemplate ( " header " , " <h1>{% render(content, {title = title}) %}</h1> " )
fm . render ( " header " , { title = ' World ' , content = ' hello ' })
This example renders either <h1>Hello, World!</h1>
or <h1>Bye, World!</h1>
depending on the value of the content
parameter.
Using blocks allows defining template fragments that can (optionally) be overwritten from other templates (usually called "child" or "inherited" templates). The following example demonstrates this approach:
fm . setTemplate ( " header " , [[
<h1>
{% function block.greet() %} -- define a (default) block
Hi
{% end %}
{% block.greet() %}, -- render the block
{%& title %}!
</h1>
]] )
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 <h1>Hello, World!</h1>
fm . render ( " bye " , { title = ' World ' }) -- renders `<h1>Bye, World!</h1>`
fm . render ( " header " , { title = ' World ' }) -- renders `<h1>Hi, World!</h1>`
In this example the header
template becomes the "layout" and defines the greet
block with Hi
as its content. The block is defined as a function in the block
table with the content it needs to produce. It's followed by a call to the block.greet
function to include its content in the template.
This is important to emphasize, as in addition to defining a block, it also needs to be called from the base/layout template at the point where it is expected to be rendered.
The hello
template also defines block.greet
function with a different content and then renders the header
template. When the header
template is rendered, it uses the content of the block.greet
function as defined in the hello
template. In this way, the child template "redefines" the greet
block with its own content, inserting it into the appropriate place into the parent template.
It works the same way for the bye
and header
templates. There is nothing special about these "block" functions other than the fact that they are defined in the block
table.
This concepts is useful for template composition at any depth. For example, let's define a modal template with a header and a footer with action buttons:
fm . setTemplate ( " modal " , [[
<div class="modal">
<div class="modal-title">
{% function block.modal_title() %}
Details
{% end %}
{% block.modal_title() %}
</div>
<div class="modal-content">
{% block.modal_content() %}
</div>
<div class="modal-actions">
{% function block.modal_actions() %}
<button>Cancel</button>
<button>Save</button>
{% end %}
{% block.modal_actions() %}
</div>
</div>
]] )
Now, in a template that renders the modal, the blocks can be overwritten to customize the content:
fm . setTemplate ( " page " , [[
{% function block.modal_title() %}
Insert photo
{% end %}
{% function block.modal_content() %}
<div class="photo-dropzone">Upload photo here</div>
{% end %}
{% render('modal') %}
]] )
This enables easily building composable layouts and components, such as headers and footers, cards, modals, or anything else that requires the ability to dynamically customize sections in other templates.
Here is an example to illustrate how nested blocks work together:
-- 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
In this example the "child" template "extends" the base template and any block.greet
content defined in the child template is rendered inside the "base" template (when and where the block.greet()
function is called). The default block.greet
block doesn't need to be defined in the base template, but when it is present (step 1), it sets the content to be rendered (step 2) if the block is not overwritten in a child template and needs to be defined before block.greet
function is called.
Similarly, block.greet
in the child template needs to be defined before (step 3) the base template is rendered (step 4) to have a desired effect.
If one of the templates in the current render tree doesn't define the block, then the later defined block is going to be used. For example, if the grandchild template doesn't define the block in step 5, then the greet
block from the child template is going to be used when the grandchild template is rendered.
If none of the block.greet
functions is defined, then block.greet()
fails (in the base
template). To make the block optional , just check the function before calling. For example, block.greet and block.greet()
.
In those cases where the "overwritten" block may still need to be rendered, it's possible to reference that block directly from the template that defines it, as shown in the following example:
fm . setTemplate ( " header " , [[
<h1>
{% function block.greet() %}
Hi
{% end %}
{% block.greet() %}, {%& title %}!
</h1>
]] )
fm . setTemplate ( " bye " , [[
{% block.header.greet() %},
{% function block.greet() %}
Bye
{% end %}
{% render('header', {title=title}) %}!
]] )
fm . render ( " bye " , { title = ' World ' }) -- renders `<h1>Hi, Bye, World!</h1>`
In this case, {% block.header.greet() %}
in the bye
template renders the greet
block from the header
template. This only works with the templates that are currently being rendered and is intended to simulate the "super" reference (albeit with explicit template references). The general syntax of this call is block.<templatename>.<blockname>()
.
As blocks are simply regular Lua functions, there are no restrictions on how blocks can be nested into other blocks or how blocks are defined relative to template fragments or other Lua statements included in the templates.
In addition to registering templates from a string, the templates can be loaded and registered from a file or a directory using the same setTemplate
function, but passing a table with the directory and a list of mappings from file extensions to template types to load. For example, calling fm.setTemplate({"/views/", tmpl = "fmt"})
loads all *.tmpl
files from the /views/
directory (and its subdirectories) and registers each of them as the fmt
template, which is the default template type. Only those files that match the extension are loaded and multiple extension mappings can be specified in one call.
Each loaded template gets its name based on the full path starting from the specified directory: the file /views/hello.tmpl
is registered as a template with the name "hello" (without the extension), whereas the file /views/greet/bye.tmpl
is registered as a template with the name "greet/bye" (and this is the exact name to use to load the template).
There are two caveats worth mentioning, both related to the directory processing. The first one is related to the trailing slash in the directory name passed to setTemplate
. It's recommended to provide one, as the specified value is used as a prefix, so if /view
is specified, it's going to match both /view/
and /views/
directories (if present), which may or may not be the intended result .
The second caveat is related to how external directories are used during template search. Since redbean allows access to external directories when configured using the -D
option or directory
option (see Running application for details), there may be multiple locations for the same template available. The search for the template follows these steps:
setTemplate
call); This allows to have a working copy of a template to be modified and processed from the file system (assuming the -D
option is used) during development without modifying its copy in the archive.
Even though using fm.render
is sufficient to get a template rendered, for consistency with other serve* functions, the library provides the serveContent
function, which is similar to fm.render
, but allows the action handler to complete after serving the content:
fm . setTemplate ( " hello " , " Hello, {%& name %} " )
fm . setRoute ( " /hello/:name " , function ( r )
return fm . serveContent ( " hello " , { name = r . params . name })
end )
There is also one subtle difference between render
and serveContent
methods that comes into play when serving static templates . It may be tempting to directly render a static template in response to a route with something like this:
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
The first approach is not going to work, as the call to fm.render
is going to be made when setRoute
is called (and the route is only being set up) and not when a request is being handled. When the serveContent
method is using (the second option), it's implemented in a way that delays the processing until the request is handled, thus avoiding the issue. If the template content depends on some values in the request, then the serverContent
call has to be wrapped into a function to accept and pass those variables (as shown in the earlier /hello/:name
route example).
Most of the time, the library configuration is focused on handling of incoming requests, but in some cases it may be desirable to trigger and handle internal events. The library supports job scheduling using cron syntax, with configured jobs executed at the scheduled time (as long as the redbean instance is running). A new schedule can be registered using the setSchedule
method:
---- ----------- ┌─────────── 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 )
All the standard and some non-standard cron expressions are supported:
*
: describes any values in the allowed range.,
: uses to form a list of items, for example, 1,2,3
.-
: creates an (inclusive) range; for example, 1-3
is equivalent to 1,2,3
. Open ranges are allowed as well, so -3
is equivalent to 1-3
for months and 0-3
for minutes and hours./
: describes a step for ranges. It selects a subset of the values in the range, using the step value; for example, 2-9/3
is equivalent to 2,5,8
(it starts with 2, then adds a step value to get 5 and 8). Non-numeric values are supported for months ( Jan-Dec
) and days of week ( Sun-Mon
) in any capitalization. Using 7
for Sun
is supported too.
By default all functions are executed in a separate (forked) process. If the execution within the same process is needed, then setSchedule
can be passed a third parameter (a table) to set sameProc
value as one of the options: {sameProc = true}
.
Some of the caveats to be aware of:
OnServerHeartbeat
hook, so a version of Redbean that provides that (v2.0.16+) should be used.and
(instead of an or
), so when both are specified, the job is executed when both are satisfied (and not when both or either are specified). In other words, * * 13 * Fri
is only valid on Friday the 13th and not on any Friday. If the or
behavior is needed, then the schedule can be split into two to handle each condition separately.sameProc = true
option to avoid forking.Sun
available on both ends (as 0 or 7), so it's better to use closed ranges in this case to avoid ambiguity.6-100
for months is corrected to 6-12
.Each action handler generates some sort of response to send back to the client. In addition to strings, the application can return the following results:
serveResponse
),serveContent
),serveRedirect
),serveAsset
),serveError
),serveIndex
), andservePath
). Each of these methods can be used as the return value from an action handler. serveAsset
, servePath
, and serveIndex
methods can also be used as action handlers directly:
fm . setRoute ( " /static/* " , fm . serveAsset )
fm . setRoute ( " /blog/ " , fm . serveIndex ( " /new-blog/ " ))
The first route configures all existing assets to be served from /static/*
location; the second route configures /blog/
URL to return the index ( index.lua
or index.html
resource) from /new-blog/
directory.
serveResponse(status[, headers][, body])
: sends an HTTP response using provided status
, headers
, and body
values. headers
is an optional table populated with HTTP header name/value pairs. If provided, this set of headers removes all other headers set earlier during the handling of the same request. Similar to the headers set using the request.headers
field, the names are case-insensitive , but provided aliases for header names with dashes are case-sensitive : {ContentType = "foo"}
is an alternative form for {["Content-Type"] = "foo"}
. body
is an optional string.
Consider the following example:
return fm . serveResponse ( 413 , " Payload Too Large " )
This returns the 413 status code and sets the body of the returned message to Payload Too Large
(with the header table not specified).
If only the status code needs to be set, the library provides a short form using the serve###
syntax:
return fm . serve413
It can also be used as the action handler itself:
fm . setRoute ( fm . PUT " /status " , fm . serve402 )
serveContent(name, parameters)
renders a template using provided parameters. name
is a string that names the template (as set by a setTemplate
call) and parameters
is a table with template parameters (referenced as variables in the template).
Fullmoon's function makeStorage
is a way to connect to, and use a SQLite3
database. makeStorage
returns a database management table which contains a rich set of functions to use with the connected database.
The run
method executes the configured application. By default the server is launched listening on localhost and port 8080. Both of these values can be changed by passing addr
and port
options:
fm . run ({ addr = " localhost " , port = 8080 })
The following options are supported; the default values are shown in parentheses and options marked with mult
can set multiple values by passing a table:
addr
: sets the address to listen on (mult)brand
: sets the Server
header value ( "redbean/v# fullmoon/v#"
)cache
: configures Cache-Control
and Expires
headers (in seconds) for all static assets served. A negative value disables the headers. Zero value means no cache.certificate
: sets the TLS certificate value (mult)directory
: sets local directory to serve assets from in addition to serving them from the archive within the executable itself (mult)headers
: sets default headers added to each response by passing a table with HTTP header name/value pairslogMessages
: enables logging of response headerslogBodies
: enables logging of request bodies (POST/PUT/etc.)logPath
: sets the log file path on the local file systempidPath
: sets the pid file path on the local file systemport
: sets the port number to listen on (8080)privateKey
: sets the TLS private key value (mult)sslTicketLifetime
: sets the duration (in seconds) of the ssl ticket (86400)trustedIp
: configures IP address to trust (mult). This option accepts two values (IP and CIDR values), so they need to be passed as a table within a table specifying multiple parameters: trustedIp = {{ParseIp("103.31.4.0"), 22}, {ParseIp("104.16.0.0"), 13}}
tokenBucket
: enables DDOS protection. This option accepts zero to 5 values (passed as a table within a table); an empty table can be passed to use default values: tokenBucket = {{}}
Each option can accept a simple value ( port = 80
), a list of values ( port = {8080, 8081}
) or a list of parameters. Since both the list of values and the list of parameters are passed as tables, the list of values takes precedence, so if a list of parameters needs to be passed to an option (like trustedIp
), it has to be wrapped into a table: trustedIp = {{ParseIp("103.31.4.0"), 22}}
. If only one parameter needs to be passed, then both trustedIp = {ParseIp("103.31.4.0")}
and trustedIp = ParseIp("103.31.4.0")
can work.
The key
and certificate
string values can be populated using the getAsset
method that can access both assets packaged within the webserver archive and those stored in the file system.
There are also default cookie and session options that can be assigned using cookieOptions
and sessionOptions
tables described below.
cookieOptions
sets default options for all cookie values assigned using request.cookie.name = value
syntax ( {httponly=true, samesite="Strict"}
). It is still possible to overwrite default values using table assignment: request.cookie.name = {value, secure=false}
.
sessionOptions
sets default options for the session value assigned using request.session.attribute = value
syntax ( {name="fullmoon_session", hash="SHA256", secret=true, format="lua"}
). If the secret
value is set to true
, then a random key is assigned each time the server is started ; if verbose logging is enabled (by either adding -v
option for Redbean or by using fm.setLogLevel(fm.kLogVerbose)
call), then a message is logged explaining how to apply the current random value to make it permanent.
Setting this value to false
or an empty string applies hashing without a secret key.
The results shown are from runs in the same environment and on the same hardware as the published redbean benchmark (thanks to @jart for executing the tests!). Even though these tests are using pre-1.5 version of redbean and 0.10 version of Fullmoon, the current versions of redbean/Fullmoon are expected to deliver similar performance.
The tests are using exactly the same code that is shown in the introduction with one small change: using {%= name %}
instead of {%& name %}
in the template, which skips HTML escaping. This code demonstrates routing, parameter handling and template processing.
$ wrk -t 12 -c 120 http://127.0.0.1:8080/user/paul Running 10s test @ http://127.0.0.1:8080/user/paul 12 threads and 120 connections Thread Stats Avg Stdev Max +/- Stdev Latency 312.06us 4.39ms 207.16ms 99.85% Req/Sec 32.48k 6.69k 71.37k 82.25% 3913229 requests in 10.10s, 783.71MB read Requests/sec: 387477.76 Transfer/sec: 77.60MB
The following test is using the same configuration, but redbean is compiled with MODE=optlinux
option:
$ wrk -t 12 -c 120 http://127.0.0.1:8080/user/paul Running 10s test @ http://127.0.0.1:8080/user/paul 12 threads and 120 connections Thread Stats Avg Stdev Max +/- Stdev Latency 346.31us 5.13ms 207.31ms 99.81% Req/Sec 36.18k 6.70k 90.47k 80.92% 4359909 requests in 10.10s, 0.85GB read Requests/sec: 431684.80 Transfer/sec: 86.45MB
The following two tests demonstrate the latency of the request handling by Fullmoon and by redbean serving a static asset (no concurrency):
$ wrk -t 1 -c 1 http://127.0.0.1:8080/user/paul Running 10s test @ http://127.0.0.1:8080/user/paul 1 threads and 1 connections Thread Stats Avg Stdev Max +/- Stdev Latency 15.75us 7.64us 272.00us 93.32% Req/Sec 65.54k 589.15 66.58k 74.26% 658897 requests in 10.10s, 131.96MB read Requests/sec: 65241.45 Transfer/sec: 13.07MB
The following are the results from redbean itself on static compressed assets:
$ wrk -H 'Accept-Encoding: gzip' -t 1 -c 1 htt://10.10.10.124:8080/tool/net/demo/index.html Running 10s test @ htt://10.10.10.124:8080/tool/net/demo/index.html 1 threads and 1 connections Thread Stats Avg Stdev Max +/- Stdev Latency 7.40us 1.95us 252.00us 97.05% Req/Sec 129.66k 3.20k 135.98k 64.36% 1302424 requests in 10.10s, 1.01GB read Requests/sec: 128963.75 Transfer/sec: 102.70MB
Berwyn Hoyt included Redbean results in his lua server benchmark results, which shows redbean outperforming a comparable nginx/openresty implementation.
Highly experimental with everything being subject to change.
The core components are more stable and have been rarely updated since v0.3. Usually, the documented interfaces are much more stable than undocumented ones. Those commits that modified some of the interfaces are marked with COMPAT
label, so can be easily identified to review for any compatibility issues.
Some of the obsolete methods are still present (with a warning logged when used) to be removed later.
Paul Kulchenko ([email protected])
See LICENSE.