123 lines
2.4 KiB
Markdown
123 lines
2.4 KiB
Markdown
# app-api
|
||
|
||
基于 [Gin](https://github.com/gin-gonic/gin) 的 Go HTTP API 脚手架。
|
||
|
||
## 项目结构
|
||
|
||
```
|
||
app-api/
|
||
├── cmd/server/ # 程序入口
|
||
├── internal/
|
||
│ ├── config/ # 配置加载
|
||
│ ├── handler/ # HTTP 处理器
|
||
│ ├── middleware/ # 中间件(日志、CORS、Request ID)
|
||
│ ├── response/ # 统一 JSON 响应
|
||
│ └── router/ # 路由注册
|
||
└── pkg/logger/ # 可复用日志封装
|
||
```
|
||
|
||
## 快速开始
|
||
|
||
### 环境要求
|
||
|
||
- Go 1.22+
|
||
|
||
### 安装依赖
|
||
|
||
```bash
|
||
go mod tidy
|
||
```
|
||
|
||
### 配置(可选)
|
||
|
||
复制环境变量示例:
|
||
|
||
```bash
|
||
cp .env.example .env
|
||
```
|
||
|
||
| 变量 | 默认值 | 说明 |
|
||
|------|--------|------|
|
||
| `APP_ENV` | `development` | 运行环境 |
|
||
| `APP_HOST` | `0.0.0.0` | 监听地址 |
|
||
| `APP_PORT` | `8080` | 监听端口 |
|
||
| `GIN_MODE` | `debug` | Gin 运行模式 |
|
||
|
||
### 数据库
|
||
|
||
根据 `APP_ENV` 自动选择 MySQL 配置;也可通过 `DATABASE_*` 环境变量完全覆盖。
|
||
|
||
| 环境 | `APP_ENV` | 默认连接 |
|
||
|------|-----------|----------|
|
||
| 开发 | `development` | `localhost:3306/audio`,用户 `root`,密码 `root123` |
|
||
| 正式 | `production` | AWS RDS `database-1.chmuueamo72p.eu-central-1.rds.amazonaws.com:3306/audio` |
|
||
|
||
正式环境密码**必须**通过环境变量 `DATABASE_PASSWORD` 提供(不要写入代码仓库)。可参考 `.env.production.example`。
|
||
|
||
开发环境可在 `.env` 中覆盖:
|
||
|
||
```bash
|
||
DATABASE_HOST=localhost
|
||
DATABASE_PORT=3306
|
||
DATABASE_NAME=audio
|
||
DATABASE_USER=root
|
||
DATABASE_PASSWORD=root123
|
||
```
|
||
|
||
正式环境启动示例(PowerShell):
|
||
|
||
```powershell
|
||
$env:APP_ENV = "production"
|
||
$env:DATABASE_PASSWORD = "your-production-password"
|
||
go run ./cmd/server
|
||
```
|
||
|
||
### 运行
|
||
|
||
```bash
|
||
make run
|
||
# 或
|
||
go run ./cmd/server
|
||
```
|
||
|
||
### 健康检查
|
||
|
||
```bash
|
||
curl http://localhost:8080/api/v1/health
|
||
```
|
||
|
||
响应示例:
|
||
|
||
```json
|
||
{
|
||
"code": 0,
|
||
"message": "ok",
|
||
"data": {
|
||
"status": "up"
|
||
}
|
||
}
|
||
```
|
||
|
||
### 品牌列表
|
||
|
||
```bash
|
||
# 查询全部
|
||
curl "http://localhost:8080/audio/getBrand"
|
||
|
||
# 按名称模糊查询
|
||
curl "http://localhost:8080/audio/getBrand?brandName=sony"
|
||
```
|
||
|
||
## 添加新接口
|
||
|
||
1. 在 `internal/handler/` 新建 handler
|
||
2. 在 `internal/router/router.go` 的 `/api/v1` 分组下注册路由
|
||
3. 使用 `internal/response` 返回统一格式
|
||
|
||
## 构建
|
||
|
||
```bash
|
||
make build
|
||
./bin/server
|
||
```
|