www.sh框架进阶指南:实现复杂路由与控制器逻辑的完整教程 www.sh框架进阶指南实现复杂路由与控制器逻辑的完整教程【免费下载链接】www.shWeb framework in Bash项目地址: https://gitcode.com/gh_mirrors/ww/www.sh想要在Bash中构建功能强大的Web应用吗www.sh框架为您提供了完整的Web开发解决方案这个创新的Bash Web框架让您能够使用熟悉的Shell脚本语言创建动态网站实现复杂的路由系统和控制器逻辑。在本终极指南中我将带您深入了解如何利用www.sh框架的高级功能构建专业的Web应用程序。 为什么选择www.sh框架www.sh是一个基于Bash的Web框架它完全颠覆了传统Web开发的方式。通过这个框架您可以使用纯Bash脚本创建功能齐全的Web应用享受以下优势零学习成本如果您熟悉Bash就能立即开始开发轻量级部署无需安装复杂的运行时环境极致性能直接使用系统原生工具运行效率极高完全控制所有代码都在您的掌握之中 项目结构深度解析让我们先来看看www.sh框架的典型项目结构项目根目录/ ├── code/ │ ├── controllers/ # 控制器目录 │ │ ├── index.sh # 首页控制器 │ │ └── view-source.sh # 查看源码控制器 │ ├── views/ # 视图模板目录 │ │ └── index.html # 首页模板 │ └── www.sh # 框架核心库 ├── www/ │ └── index.cgi # CGI入口点 └── .env # 环境配置文件 核心路由系统详解www.sh的路由系统简洁而强大。在框架核心文件code/www.sh中路由功能通过关联数组实现# 路由注册示例 route / index route /about about route /users/:id user_profile路由匹配逻辑位于http_serve函数中它会根据REQUEST_URI查找对应的控制器并执行# 路由匹配核心代码简化版 local request${REQUEST_URI%%\?*} [[ $request ]] request/ if [[ -n ${routes[$request]} ]]; then local controller${routes[$request]} content$(source ../code/controllers/$controller.sh) else http_status 404 Not Found contentNot Found fi 高级控制器设计模式基础控制器示例查看code/controllers/index.sh文件您可以看到一个简单的控制器实现# 设置模板变量 tmpl[welcome]${_GET[welcome]} tmpl[sw-ver]www.sh $WWWSH_VERSION tmpl[sw-url]$WWWSH_URL # 渲染视图 printf %s $(view index.html)复杂业务逻辑控制器让我们创建一个更复杂的用户管理控制器# code/controllers/users.sh # 用户管理控制器示例 # 检查用户权限 if [[ -z ${_SESSION[user_id]} ]]; then http_status 401 Unauthorized tmpl[error]请先登录 printf %s $(view login.html) exit 0 fi # 处理不同HTTP方法 case $REQUEST_METHOD in GET) # 获取用户列表 users$(query SELECT id, username FROM users LIMIT 50) tmpl[users]$users printf %s $(view users_list.html) ;; POST) # 创建新用户 username$(html ${_POST[username]}) email$(html ${_POST[email]}) # 数据验证 if [[ -z $username || -z $email ]]; then tmpl[error]用户名和邮箱不能为空 printf %s $(view user_form.html) exit 0 fi # 执行数据库操作 query INSERT INTO users (username, email) VALUES ($username, $email) http_status 303 See Other http_header Location /users printf ;; *) http_status 405 Method Not Allowed printf Method Not Allowed ;; esac 视图模板系统实战www.sh的模板系统简单而实用。查看code/views/index.html文件html head titlewww.sh/title /head body h1Welcome to www.sh - the experimental bash web framework/h1 pHi {{welcome}}/p pPowered by {{sw-ver}} ({{sw-url}})/p /body /html高级模板技巧创建动态内容循环!-- users_list.html -- html head title用户列表/title /head body h1用户管理/h1 table tr thID/th th用户名/th th操作/th /tr {{users_rows}} /table /body /html在控制器中动态生成表格行# 生成用户表格行 users_data$(query SELECT id, username FROM users) rows while IFS$\t read -r id username; do rowstrtd$id/tdtd$username/td rowstda href/users/$id/edit编辑/a/td/tr done $users_data tmpl[users_rows]$rows 安全与数据验证输入过滤与消毒www.sh提供了内置的安全函数# HTML转义 safe_input$(html $user_input) # SQL参数化十六进制编码 user_id$(sql $user_id) querySELECT * FROM users WHERE id $user_id # URL编解码 encoded$(url_encode $data) decoded$(url_decode $encoded)会话管理实现虽然www.sh没有内置会话系统但您可以轻松实现# 简单的Cookie-based会话 session_id$(uuidgen) http_header Set-Cookie session_id$session_id; HttpOnly; Path/ # 验证会话 if [[ $HTTP_COOKIE ~ session_id([^;]) ]]; then session_id${BASH_REMATCH[1]} # 验证session_id的有效性 fi️ 项目配置与环境管理环境变量配置使用.env文件管理配置# .env 文件示例 DB_HOSTlocalhost DB_USERapp_user DB_PASSsecure_password DB_DATABASEmyapp APP_DEBUGfalse在控制器中访问环境变量# 访问配置 db_host${_ENV[DB_HOST]} db_user${_ENV[DB_USER]} # 数据库查询 results$(query SELECT * FROM products WHERE active 1) 错误处理与日志记录自定义错误页面# 错误处理函数 handle_error() { local error_code$1 local message$2 http_status $error_code tmpl[error_code]$error_code tmpl[error_message]$message printf %s $(view error.html) exit 0 } # 使用示例 if [[ -z ${_GET[id]} ]]; then handle_error 400 Bad Request 缺少必要参数 fi请求日志记录# 记录访问日志 log_request() { local timestamp$(date %Y-%m-%d %H:%M:%S) local ip${REMOTE_ADDR:-unknown} local method$REQUEST_METHOD local uri$REQUEST_URI local status$http_status_code echo [$timestamp] $ip $method $uri $status ../logs/access.log } # 在http_serve函数末尾调用 log_request 性能优化技巧缓存策略# 简单的文件缓存 cache_page() { local cache_key$1 local content$2 local cache_file../cache/${cache_key}.html # 缓存1小时 echo $content $cache_file echo $(date %s) ${cache_file}.timestamp } # 检查缓存 get_cached_page() { local cache_key$1 local cache_file../cache/${cache_key}.html local timestamp_file${cache_file}.timestamp if [[ -f $cache_file -f $timestamp_file ]]; then local cache_time$($timestamp_file) local current_time$(date %s) local age$((current_time - cache_time)) # 缓存1小时内有效 if [[ $age -lt 3600 ]]; then cat $cache_file return 0 fi fi return 1 }数据库连接池# 复用数据库连接 db_query() { local query$1 local db_socket/tmp/mysql.sock # 使用命名管道避免密码暴露 mysql --socket$db_socket \ --user${_ENV[DB_USER]} \ --database${_ENV[DB_DATABASE]} \ --silent --raw $query | tail -n 2 } 测试与调试单元测试示例#!/bin/bash # test_controllers.sh source ../code/www.sh # 测试路由系统 test_routing() { echo 测试路由系统... # 模拟路由注册 route /test test # 验证路由存在 if [[ -n ${routes[/test]} ]]; then echo ✓ 路由注册成功 else echo ✗ 路由注册失败 exit 1 fi } # 测试模板系统 test_templates() { echo 测试模板系统... tmpl[test_var]测试值 result$(view test_template.html) if [[ $result *测试值* ]]; then echo ✓ 模板渲染成功 else echo ✗ 模板渲染失败 exit 1 fi } # 运行测试 test_routing test_templates echo 所有测试通过 部署最佳实践Docker容器化部署查看项目中的Dockerfile了解如何容器化您的www.sh应用FROM alpine:latest # 安装依赖 RUN apk add --no-cache bash mysql-client # 复制应用文件 COPY . /app WORKDIR /app # 设置权限 RUN chmod x www/index.cgi # 启动服务 CMD [/usr/sbin/httpd, -f, -h, /app/www]Apache配置使用项目中的docker/httpd.conf作为参考# Apache虚拟主机配置 VirtualHost *:80 DocumentRoot /var/www/html ScriptAlias /cgi-bin/ /var/www/cgi-bin/ Directory /var/www/cgi-bin AllowOverride None Options ExecCGI Require all granted /Directory /VirtualHost 实际应用场景场景1RESTful API开发# code/controllers/api/products.sh case $REQUEST_METHOD in GET) if [[ -n ${_GET[id]} ]]; then # 获取单个产品 product_id$(sql ${_GET[id]}) result$(query SELECT * FROM products WHERE id $product_id) http_header Content-Type application/json printf {product: %s} $result else # 获取产品列表 result$(query SELECT * FROM products LIMIT 100) http_header Content-Type application/json printf {products: [%s]} $result fi ;; POST) # 创建新产品 name$(html ${_POST[name]}) price${_POST[price]} query INSERT INTO products (name, price) VALUES ($name, $price) http_status 201 Created printf {status: created, id: %s} $(mysql_insert_id) ;; esac场景2文件上传处理# code/controllers/upload.sh if [[ $HTTP_CONTENT_TYPE multipart/form-data ]]; then # 解析multipart/form-data boundary${HTTP_CONTENT_TYPE#*} # 保存上传的文件 temp_file$(mktemp) cat $temp_file # 处理文件内容 # ... 文件处理逻辑 ... tmpl[message]文件上传成功 printf %s $(view upload_success.html) fi 总结与下一步通过本指南您已经掌握了www.sh框架的核心概念和高级技巧。这个Bash Web框架虽然简单但功能强大足以构建复杂的Web应用。关键收获✅ 掌握了www.sh的路由系统设计✅ 学会了创建复杂的控制器逻辑✅ 理解了模板系统的使用方式✅ 掌握了安全最佳实践✅ 学会了性能优化技巧下一步建议从简单的CRUD应用开始实践尝试集成数据库操作实现用户认证系统构建RESTful API优化应用性能记住www.sh框架最适合内部工具、管理界面和小型项目。对于高流量生产环境建议使用更成熟的Web框架。现在就开始您的Bash Web开发之旅吧使用www.sh框架您将发现用Shell脚本构建Web应用原来如此简单而有趣 【免费下载链接】www.shWeb framework in Bash项目地址: https://gitcode.com/gh_mirrors/ww/www.sh创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考