diff --git a/examples/web-site/components/nav.mq.md b/examples/web-site/components/nav.mq.md
index c6518b3..7f157a6 100644
--- a/examples/web-site/components/nav.mq.md
+++ b/examples/web-site/components/nav.mq.md
@@ -7,6 +7,7 @@ Static top links for the shell.
| 属性 | 值 | 样式 |
|------|-----|------|
| Home | / | |
+| About | /about | |
| New | /_form/article | |
| Admin | /admin | |
diff --git a/examples/web-site/index.mq.md b/examples/web-site/index.mq.md
index edc011d..8bd34bf 100644
--- a/examples/web-site/index.mq.md
+++ b/examples/web-site/index.mq.md
@@ -1,6 +1,6 @@
---
title: web-site
-description: Home = page table; main inline; class methods assemble; form §5.5.
+description: Home + /about route + form §5.5 + admin.
> ext/web/web.mq.md
> styles/shell.mq.md
> components/nav.mq.md
@@ -51,10 +51,16 @@ Article create form (design §5.5): field table + rules table.
*`page` = > `page`.compose_components components=`home` *
*`page` = > `page`.compose_main main=`index` *
+About page: same shell, different intro (no main bind).
+
+*`about` = > web.page title="About" intro="
About
Marqdo web = tables + class methods.
" *
+*`about` = > `about`.compose_components components=`home` *
+
*`article_form` = > web.form table=articles action=insert *
*`article_form` = > `article_form`.fields fields=`article_fields` *
*`article_form` = > `article_form`.rules rules=`article_rules` *
*`app` = > web.app page=`page` db=`store` admin=True host=127.0.0.1 port=18081 *
+*`app` = > `app`.route path=/about page=`about` *
*`app` = > `app`.mount_form id=article form=`article_form` *
> `app`.listen
diff --git a/ext/web/README.md b/ext/web/README.md
index 8eaa31a..9289588 100644
--- a/ext/web/README.md
+++ b/ext/web/README.md
@@ -27,4 +27,5 @@ Offline smokes: `tests/ext/web-smoke.mq.md`, `web-form-smoke.mq.md`, `web-admin-
| Feature | Notes |
|---------|--------|
| Form §5.5 | field/rules tables · `validate` · `submit` · `mount_form` → `GET\|POST /_form/{id}` |
-| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` |
\ No newline at end of file
+| Admin CRUD | `admin=True` · schema → same form path · new/edit/delete under `/admin/{table}` |
+| Route | `` `app`.route path=/about page=`about` `` → `GET /about` |
\ No newline at end of file
diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md
index 45ce23b..ce861c7 100644
--- a/ext/web/web.mq.md
+++ b/ext/web/web.mq.md
@@ -174,9 +174,11 @@ Field table + rules table; submit writes through `# db`.
## route
+ `path`
- + `page`=None
+ + `page`
-**`self`**
+Mount an assembled page at `path` (e.g. `/about`). `/` is the home `page=`.
+
+**> web_app_route app=`self` path=`path` page=`page`**
## mount_form
+ `id`
@@ -188,6 +190,6 @@ Register `GET|POST /_form/{id}` for listen.
## listen
-Serve `/`, `/_part/{id}`, `/_form/{id}`, and optional `/admin`.
+Serve `/`, routed pages, `/_part/{id}`, `/_form/{id}`, and optional `/admin`.
**> web_listen app=`self`**
diff --git a/ext/web/网页.mq.md b/ext/web/网页.mq.md
index 2b6c2b1..b143c72 100644
--- a/ext/web/网页.mq.md
+++ b/ext/web/网页.mq.md
@@ -166,9 +166,11 @@ description: 官方网站类(中文)。表格 + 方法;不写袋式胶水
## 路由
+ `路径`
- + `页面`=None
+ + `页面`
-**`self`**
+将已装配页面挂到 `路径`(如 `/about`)。`/` 由首页 `页面=` 提供。
+
+**> web_app_route app=`self` path=`路径` page=`页面`**
## 挂载表单
+ `id`
diff --git a/plugins/web/src/http.rs b/plugins/web/src/http.rs
index 3f36f7a..c10666d 100644
--- a/plugins/web/src/http.rs
+++ b/plugins/web/src/http.rs
@@ -5,6 +5,7 @@ use std::net::SocketAddr;
use std::sync::Arc;
use axum::extract::{Form, Path, State};
+use axum::http::Uri;
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::get;
use axum::Router;
@@ -21,6 +22,7 @@ struct AppState {
db_url: Option,
admin: bool,
forms: HashMap,
+ routes: HashMap,
}
pub fn listen(
@@ -30,15 +32,17 @@ pub fn listen(
port: u16,
admin: bool,
forms: HashMap,
+ routes: HashMap,
) -> Result {
let state = Arc::new(AppState {
page: page.clone(),
db_url: db_url.map(|s| s.to_string()),
admin,
forms,
+ routes: routes.clone(),
});
- let app = Router::new()
+ let mut app = Router::new()
.route("/", get(home))
.route("/_part/{id}", get(part))
.route("/_form/{id}", get(form_get).post(form_post))
@@ -49,8 +53,16 @@ pub fn listen(
"/admin/{table}/{id}/edit",
get(admin_edit_get).post(admin_edit_post),
)
- .route("/admin/{table}/{id}/delete", get(admin_delete))
- .with_state(state);
+ .route("/admin/{table}/{id}/delete", get(admin_delete));
+
+ // Register each author route as an exact GET path.
+ let mut paths: Vec = routes.keys().cloned().collect();
+ paths.sort();
+ for path in paths {
+ app = app.route(&path, get(routed_page));
+ }
+
+ let app = app.with_state(state);
let addr: SocketAddr = format!("{host}:{port}")
.parse()
@@ -74,6 +86,17 @@ async fn home(State(st): State>) -> Html {
Html(html)
}
+async fn routed_page(State(st): State>, uri: Uri) -> Response {
+ let mut path = uri.path().to_string();
+ while path.len() > 1 && path.ends_with('/') {
+ path.pop();
+ }
+ let Some(page) = st.routes.get(&path) else {
+ return Html(format!("404 not found: {}
", esc(&path))).into_response();
+ };
+ Html(render::render_page(page, st.db_url.as_deref())).into_response()
+}
+
async fn part(State(st): State>, Path(id): Path) -> Response {
let Some(parts) = st.page.get("parts").and_then(|v| v.as_object()) else {
return Html(String::from("no parts
")).into_response();
diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs
index 703a2f1..36ac13c 100644
--- a/plugins/web/src/lib.rs
+++ b/plugins/web/src/lib.rs
@@ -332,9 +332,59 @@ web_ffi!(web_app_new, |args: &Value| {
"port": port,
"admin": admin,
"forms": {},
+ "routes": {},
}))
});
+fn normalize_route_path(raw: &str) -> Result {
+ let s = raw.trim();
+ if s.is_empty() {
+ return Err("route path is empty".into());
+ }
+ if s == "/" {
+ return Err("route path `/` is reserved for the home page".into());
+ }
+ let mut path = if s.starts_with('/') {
+ s.to_string()
+ } else {
+ format!("/{s}")
+ };
+ while path.len() > 1 && path.ends_with('/') {
+ path.pop();
+ }
+ // reserved prefixes
+ if path == "/admin"
+ || path.starts_with("/admin/")
+ || path == "/_form"
+ || path.starts_with("/_form/")
+ || path == "/_part"
+ || path.starts_with("/_part/")
+ {
+ return Err(format!("route path `{path}` is reserved"));
+ }
+ Ok(path)
+}
+
+web_ffi!(web_app_route, |args: &Value| {
+ let mut app = args.get("app").cloned().unwrap_or(json!({}));
+ let path = normalize_route_path(arg_str(args, "path")?)?;
+ let page = args
+ .get("page")
+ .cloned()
+ .ok_or_else(|| "missing `page` for route".to_string())?;
+ let obj = app
+ .as_object_mut()
+ .ok_or_else(|| "app must be a map".to_string())?;
+ let routes = obj
+ .entry("routes".to_string())
+ .or_insert_with(|| json!({}));
+ let rmap = routes
+ .as_object_mut()
+ .ok_or_else(|| "app.routes must be a map".to_string())?;
+ rmap.insert(path, page);
+ Ok(app)
+});
+
web_ffi!(web_app_mount_form, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let id = arg_str(args, "id")?.to_string();
@@ -442,7 +492,7 @@ web_ffi!(web_db_table_info, |args: &Value| {
web_ffi!(web_listen, |args: &Value| {
use std::collections::HashMap;
- let (page, db_url, host, port, admin, forms) = if args.get("page").is_some()
+ let (page, db_url, host, port, admin, forms, routes) = if args.get("page").is_some()
|| args.get("host").is_some()
{
let page = args.get("page").cloned().unwrap_or(json!({}));
@@ -456,8 +506,15 @@ web_ffi!(web_listen, |args: &Value| {
Some(Value::Bool(b)) => *b,
_ => false,
};
- let forms = HashMap::new();
- (page, db_url, host.to_string(), port, admin, forms)
+ (
+ page,
+ db_url,
+ host.to_string(),
+ port,
+ admin,
+ HashMap::new(),
+ HashMap::new(),
+ )
} else {
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
let page = app.get("page").cloned().unwrap_or(json!({}));
@@ -486,9 +543,23 @@ web_ffi!(web_listen, |args: &Value| {
forms.insert(k.clone(), v.clone());
}
}
- (page, db_url, host, port, admin, forms)
+ let mut routes = HashMap::new();
+ if let Some(obj) = app.get("routes").and_then(|v| v.as_object()) {
+ for (k, v) in obj {
+ routes.insert(k.clone(), v.clone());
+ }
+ }
+ (page, db_url, host, port, admin, forms, routes)
};
- http::listen(&page, db_url.as_deref(), &host, port, admin, forms)
+ http::listen(
+ &page,
+ db_url.as_deref(),
+ &host,
+ port,
+ admin,
+ forms,
+ routes,
+ )
});
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
@@ -546,6 +617,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
"page,db,admin,host,port",
web_app_new as PluginFn,
),
+ ("web_app_route", "app,path,page", web_app_route as PluginFn),
(
"web_app_mount_form",
"app,id,form",
diff --git a/tests/ext/web-route-smoke.mq.md b/tests/ext/web-route-smoke.mq.md
new file mode 100644
index 0000000..d4167b1
--- /dev/null
+++ b/tests/ext/web-route-smoke.mq.md
@@ -0,0 +1,34 @@
+---
+title: web route smoke
+description: Offline app.route registration (no listen).
+> ext/web/web.mq.md
+> lib/json.mq.md
+---
+
+# main
+
+*`home` = > web.page title="Home" intro="Home
" *
+*`about` = > web.page title="About" intro="About
" *
+*`app` = > web.app page=`home` host=127.0.0.1 port=18081 *
+*`app` = > `app`.route path=/about page=`about` *
+*`app` = > `app`.route path=docs page=`about` *
+
+*`routes` = > json.get value=`app` key=routes *
+*`about_page` = > json.get value=`routes` key="/about" *
+*`docs_page` = > json.get value=`routes` key="/docs" *
+
+1. `about_page`
+ > print text=about-ok
+2. *
+ > print text=about-fail
+
+1. `docs_page`
+ > print text=docs-ok
+2. *
+ > print text=docs-fail
+
+*`html` = > `about`.render *
+1. `html`
+ > print text=render-ok
+2. *
+ > print text=render-fail
diff --git a/tests/gold.rs b/tests/gold.rs
index 2c8bdc7..3bb0634 100644
--- a/tests/gold.rs
+++ b/tests/gold.rs
@@ -1278,6 +1278,22 @@ required-ok",
);
}
+#[test]
+fn ext_web_route_smoke() {
+ let status = Command::new("cargo")
+ .args(["build", "-p", "marqdo_plugin_web"])
+ .current_dir(env!("CARGO_MANIFEST_DIR"))
+ .status()
+ .expect("build web plugin");
+ assert!(status.success(), "failed to build marqdo_plugin_web");
+ assert_out(
+ "tests/ext/web-route-smoke.mq.md",
+ "about-ok
+docs-ok
+render-ok",
+ );
+}
+
#[test]
fn ext_agent_framework_smoke() {
let status = Command::new("cargo")