net.listen({type:'web'}) 启动 BT Web 服务。每个请求都会执行站点入口 BT 文件,并注入 web 请求上下文对象。
server = net.listen({ type:'web', bind:'127.0.0.1:8080', sites:[ { domains:['127.0.0.1'], root:'web/', entry:'main.bt' } ] })
net.listen() 接收配置对象:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| type | string | 是 | 无 | 固定为 web |
| bind | string | 否 | 0.0.0.0:8080 | 监听地址,格式为 host:port |
| sites | Array | 是 | 无 | 站点配置列表,至少一个 |
站点配置字段:
| 字段 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
| domains | Array | 否 | [] | 域名列表;为空时作为默认站点 |
| root | string | 否 | web/ | BT Web 项目目录 |
| entry | string | 否 | main.bt | 请求入口 BT 文件 |
| upload.temp | string | 否 | temp/ | 上传文件临时目录 |
| static.route | string | 否 | /static/{**} | 静态资源路由 |
| static.path | string | 否 | root + 'static/' | 静态资源目录 |
| static.default | string | 否 | index.html | 静态目录默认文件 |
| static.list | bool | 否 | false | 是否允许目录列表 |
| ssl.cert | string | 否 | 无 | TLS 证书文件路径 |
| ssl.key | string | 否 | 无 | TLS 私钥文件路径 |
返回 WebServer 对象。
| 字段/方法 | 类型 | 说明 |
|---|---|---|
| addr | string | 实际监听地址 |
| type | string | 固定为 web |
| close() | fn | 关闭当前 Web 服务,返回 true |
入口文件中可以读取请求数据:
// web/main.bt name = web.get.name if name { 'hello ' + name } else { 'hello BT' }
也可以设置响应头、状态码和 JSON 内容:
web.header('Content-Type', 'application/json') web.status_code(200) json({ ok:true, url:web.url, method:web.method })
配置 static 后,匹配静态路由的请求会优先读取静态目录。
net.listen({ type:'web', bind:'127.0.0.1:8080', sites:[ { root:'examples/net-web/www/', entry:'main.bt', static:{ route:'/static/{**}', path:'examples/net-web/www/static/', default:'index.html', list:false } } ] })
sites 不能为空,否则启动失败。
BT_WEB_WORKERS 环境变量可覆盖 worker 数量。
root 和 entry 解析。
web 对象读取,例如 web.get、web.post、web.cookie、web.session。
print / println 输出;如果没有输出,则使用入口文件最后一个表达式的返回值。
Content-Type 为 text/html; charset=utf-8,可用 web.header() 覆盖。