# nginx-go **Repository Path**: larryzeal/nginx-go ## Basic Information - **Project Name**: nginx-go - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-07 - **Last Updated**: 2026-03-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # nginx-go 基于Go语言实现的轻量级nginx服务器,支持文件服务器、请求转发和前端路由支持。 ## 功能特性 - **文件服务器**:提供静态文件访问功能 - **请求转发**:支持将请求转发到后端服务器 - **前端路由支持**:当访问不存在的路径时,返回index.html,支持单页应用的前端路由 - **路径安全**:防止路径穿越攻击,确保文件访问不超出根目录 - **最长前缀匹配**:类似nginx的路由匹配策略,优先匹配最具体的路径 - **优雅关闭**:支持信号处理,确保在关闭时完成正在处理的请求 - **简单配置**:使用JSON格式配置文件,易于理解和修改 ## 快速开始 ### 1. 构建项目 ```bash go build -o nginx-go.exe ``` ### 2. 启动服务器 ```bash ./nginx-go.exe ``` 服务器默认在 `http://localhost:8080` 启动。 ### 3. 运行测试 ```bash go test -v ./... ``` ### 4. 测试功能 - **文件服务器**:访问 `http://localhost:8080/files/index.html` - **前端路由**:访问 `http://localhost:8080/some/nonexistent/path`(会返回index.html) - **请求转发**:访问 `http://localhost:8080/proxy` 会转发到 `http://localhost:3000` ## 配置说明 配置文件为 `config.json`,包含以下字段: - `port`:服务器监听端口 - `servers`:服务器配置数组 - `locations`:路径配置数组 - `path`:路径匹配规则 - `type`:路径类型,支持 `file`、`proxy` - `root`:文件服务器根目录(仅 `file` 类型需要) - `proxy_pass`:代理目标地址(仅 `proxy` 类型需要) ### 路径类型说明 1. **file**:文件服务器类型,用于提供静态文件访问 - `root`:文件服务器根目录,可以是相对路径或绝对路径 2. **proxy**:代理类型,用于将请求转发到后端服务器 ### 示例配置 ```json { "port": 8080, "servers": [ { "locations": [ { "path": "/files", "type": "file", "root": "./static" }, { "path": "/proxy", "type": "proxy", "proxy_pass": "http://localhost:3000" } ] } ] } ``` ## 项目结构 ``` nginx-go/ ├── main.go # 主入口文件 ├── config.go # 配置结构和加载函数 ├── handle.go # 请求处理逻辑 ├── config_test.go # 配置相关测试 ├── handle_test.go # 请求处理相关测试 ├── config.json # 配置文件 ├── static/ # 静态文件目录 │ └── index.html # 测试文件 └── README.md # 项目说明 ``` ## 技术栈 - **语言**:Go 1.25+ - **标准库**:net/http, net/http/httputil, encoding/json, os, path/filepath, strings ## 前端项目部署 ### 1. 准备前端构建产物 将前端项目的构建产物(如 `dist` 目录)复制到 `static` 目录中。 ### 2. 配置nginx-go 确保 `config.json` 中包含文件服务器配置,指向 `static` 目录。 ### 3. 启动服务器 ```bash ./nginx-go.exe ``` ### 4. 访问前端应用 打开浏览器访问 `http://localhost:8080`,即可看到前端应用。 ## 注意事项 - 本项目为轻量级实现,仅支持基本功能 - 不支持HTTPS - 配置文件需要手动修改,不支持热重载 - 适用于开发和测试环境,生产环境建议使用正式的nginx ## 许可证 MIT