cocoon/static.h
xfy911 dd41464b9c feat(middleware): 实现中间件框架(CORS / Basic Auth / Rate Limit)
- 新增 middleware.c/middleware.h:注册表 + 链式执行机制
  - 内置 CORS 中间件:支持预检请求、跨域头
  - 内置 Basic Auth 中间件:HTTP 基础认证
  - 内置 Rate Limit 中间件:基于 IP 的秒级限流
- 修复 config_merge 参数不匹配(新增 has_cors_enabled/has_auth_user/has_auth_pass/has_rate_limit)
- 修复 server_destroy 与 main() 双重释放字符串指针
- 修复 main.c 启动段错误(access_log_path 未初始化)
- 修复 rate_limit 哈希函数包含端口导致同一 IP 不同 bucket 的问题
- 修复 rate_limit 中间件 user_data 悬空指针(改为 ctx->mw_config)
- 修复 401/429 响应 Content-Length 与 body 长度不匹配导致 curl 挂起
- 修复集成测试服务器启动循环:使用 nc 代替 curl,避免触发限流计数
- 修复集成测试 kill_server:使用 kill -9 确保进程退出,并检查端口释放
- 单元测试 18/18 通过,集成测试 66/66 通过
2026-06-06 00:32:22 +08:00

75 lines
2.1 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* static.h - 静态资源服务模块接口
*
* @author xfy
*/
#ifndef COCOON_STATIC_H
#define COCOON_STATIC_H
#include "http.h"
#include <stdbool.h>
/**
* send_all - 确保缓冲区全部发送
*
* 使用 write 循环发送,直到全部数据发送完毕或遇到不可恢复错误。
* 内部辅助函数,也可被其他模块调用。
*
* @param fd socket 文件描述符
* @param buf 数据缓冲区
* @param len 数据长度
* @return 0 成功,-1 失败
*/
int send_all(int fd, const char *buf, size_t len);
/**
* static_serve_file - 服务单个静态文件
*
* 打开文件根据请求判断是否需要发送部分内容Range
* 然后通过 sendfile 或循环读取发送文件内容。
*
* @param fd 客户端 socket 文件描述符
* @param req HTTP 请求
* @param root_dir 静态资源根目录
* @param gzip_enabled 是否启用 gzip 压缩
* @param brotli_enabled 是否启用 brotli 压缩
* @return COCOON_OK 成功,负值错误码
*/
int static_serve_file(int fd, const http_request_t *req, const char *root_dir, bool gzip_enabled, bool brotli_enabled);
/**
* static_serve_directory - 生成目录列表 HTML
*
* 当请求路径是目录且不含默认 index.html 时,生成美观的目录浏览页面。
*
* @param fd 客户端 socket 文件描述符
* @param req HTTP 请求
* @param root_dir 静态资源根目录
* @param real_path 文件系统上的真实路径
* @return COCOON_OK 成功,负值错误码
*/
int static_serve_directory(int fd, const http_request_t *req,
const char *root_dir, const char *real_path);
/**
* static_send_error - 发送 HTTP 错误响应
*
* @param fd 客户端 socket
* @param status_code HTTP 状态码(如 404、403
* @param keep_alive 是否保持连接
* @return COCOON_OK 成功
*/
int static_send_error(int fd, int status_code, bool keep_alive);
/**
* static_set_cors - 设置是否启用 CORS 响应头
*
* 全局开关,启用后所有 HTTP 响应自动添加 Access-Control-Allow-Origin: *。
*
* @param enabled true 启用false 禁用
*/
void static_set_cors(bool enabled);
#endif /* COCOON_STATIC_H */