311 lines
6.3 KiB
Markdown
311 lines
6.3 KiB
Markdown
# 快速开始指南
|
||
|
||
5分钟快速上手 GoCommon 工具库。
|
||
|
||
## 1. 安装
|
||
|
||
```bash
|
||
# 配置私有仓库
|
||
go env -w GOPRIVATE=git.toowon.com
|
||
|
||
# 安装最新版本
|
||
go get git.toowon.com/jimmy/go-common@latest
|
||
```
|
||
|
||
## 2. 创建配置文件
|
||
|
||
创建 `config.json`:
|
||
|
||
```json
|
||
{
|
||
"database": {
|
||
"type": "mysql",
|
||
"host": "localhost",
|
||
"port": 3306,
|
||
"user": "root",
|
||
"password": "password",
|
||
"database": "mydb"
|
||
},
|
||
"redis": {
|
||
"host": "localhost",
|
||
"port": 6379
|
||
},
|
||
"logger": {
|
||
"level": "info",
|
||
"output": "stdout",
|
||
"async": true
|
||
}
|
||
}
|
||
```
|
||
|
||
## 3. 创建主程序
|
||
|
||
创建 `main.go`:
|
||
|
||
```go
|
||
package main
|
||
|
||
import (
|
||
"net/http"
|
||
"time"
|
||
|
||
"git.toowon.com/jimmy/go-common/factory"
|
||
"git.toowon.com/jimmy/go-common/middleware"
|
||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||
)
|
||
|
||
func main() {
|
||
// 从配置文件创建工厂(黑盒模式)
|
||
fac, err := factory.NewFactoryFromFile("./config.json")
|
||
if err != nil {
|
||
panic(err)
|
||
}
|
||
|
||
// 获取logger
|
||
logger, _ := fac.GetLogger()
|
||
defer logger.Close()
|
||
|
||
// 配置中间件链
|
||
chain := middleware.NewChain(
|
||
middleware.Recovery(&middleware.RecoveryConfig{Logger: logger}),
|
||
middleware.Logging(&middleware.LoggingConfig{Logger: logger}),
|
||
middleware.RateLimitByIP(100, time.Minute),
|
||
middleware.CORS(nil),
|
||
middleware.Timezone,
|
||
)
|
||
|
||
// 注册路由
|
||
http.Handle("/api/hello", chain.ThenFunc(handleHello))
|
||
http.Handle("/api/users", chain.ThenFunc(handleUsers))
|
||
|
||
// 启动服务
|
||
logger.Info("Server started on :8080")
|
||
http.ListenAndServe(":8080", nil)
|
||
}
|
||
|
||
// API处理器 - 问候接口
|
||
func handleHello(w http.ResponseWriter, r *http.Request) {
|
||
h := commonhttp.NewHandler(w, r)
|
||
|
||
h.Success(map[string]interface{}{
|
||
"message": "Hello, World!",
|
||
"timezone": h.GetTimezone(),
|
||
})
|
||
}
|
||
|
||
// API处理器 - 用户列表(带分页)
|
||
func handleUsers(w http.ResponseWriter, r *http.Request) {
|
||
h := commonhttp.NewHandler(w, r)
|
||
|
||
// 解析分页参数
|
||
pagination := h.ParsePaginationRequest()
|
||
page := pagination.GetPage()
|
||
size := pagination.GetSize()
|
||
|
||
// 模拟数据
|
||
users := []map[string]interface{}{
|
||
{"id": 1, "name": "Alice"},
|
||
{"id": 2, "name": "Bob"},
|
||
}
|
||
total := int64(100)
|
||
|
||
// 返回分页数据
|
||
h.SuccessPage(users, total, page, size)
|
||
}
|
||
```
|
||
|
||
## 4. 运行
|
||
|
||
```bash
|
||
go run main.go
|
||
```
|
||
|
||
## 5. 测试
|
||
|
||
```bash
|
||
# 测试问候接口
|
||
curl http://localhost:8080/api/hello
|
||
|
||
# 测试分页接口
|
||
curl "http://localhost:8080/api/users?page=1&page_size=10"
|
||
|
||
# 测试时区
|
||
curl -H "X-Timezone: America/New_York" http://localhost:8080/api/hello
|
||
|
||
# 测试限流(快速请求多次)
|
||
for i in {1..150}; do curl http://localhost:8080/api/hello; done
|
||
```
|
||
|
||
## 6. 常见使用场景
|
||
|
||
### 场景1:使用数据库
|
||
|
||
```go
|
||
// 获取数据库连接
|
||
db, _ := fac.GetDatabase()
|
||
|
||
// 使用GORM查询
|
||
var users []User
|
||
db.Find(&users)
|
||
```
|
||
|
||
### 场景2:使用Redis
|
||
|
||
```go
|
||
ctx := context.Background()
|
||
|
||
// 设置值
|
||
fac.RedisSet(ctx, "key", "value", time.Hour)
|
||
|
||
// 获取值
|
||
value, _ := fac.RedisGet(ctx, "key")
|
||
|
||
// 删除值
|
||
fac.RedisDelete(ctx, "key")
|
||
```
|
||
|
||
### 场景3:发送邮件
|
||
|
||
```go
|
||
// 发送简单邮件
|
||
fac.SendEmail(
|
||
[]string{"user@example.com"},
|
||
"测试邮件",
|
||
"这是邮件正文",
|
||
)
|
||
|
||
// 发送HTML邮件
|
||
fac.SendEmail(
|
||
[]string{"user@example.com"},
|
||
"测试邮件",
|
||
"纯文本内容",
|
||
"<h1>HTML内容</h1>",
|
||
)
|
||
```
|
||
|
||
### 场景4:上传文件
|
||
|
||
```go
|
||
ctx := context.Background()
|
||
|
||
// 打开文件
|
||
file, _ := os.Open("test.jpg")
|
||
defer file.Close()
|
||
|
||
// 上传文件(自动选择OSS或MinIO)
|
||
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
||
|
||
// 获取文件URL
|
||
url, _ := fac.GetFileURL("images/test.jpg", 3600) // 1小时后过期
|
||
```
|
||
|
||
### 场景5:记录日志
|
||
|
||
```go
|
||
// 简单日志
|
||
fac.LogInfo("用户登录成功")
|
||
fac.LogError("登录失败: %v", err)
|
||
|
||
// 带字段的日志
|
||
fac.LogInfof(map[string]interface{}{
|
||
"user_id": 123,
|
||
"action": "login",
|
||
}, "用户操作")
|
||
```
|
||
|
||
### 场景6:时间处理
|
||
|
||
```go
|
||
import "git.toowon.com/jimmy/go-common/datetime"
|
||
|
||
// 获取当前时间(带时区)
|
||
timezone := h.GetTimezone()
|
||
now := datetime.Now(timezone)
|
||
|
||
// 格式化时间
|
||
str := datetime.FormatDateTime(now)
|
||
|
||
// 解析时间
|
||
t, _ := datetime.ParseDateTime("2024-01-01 00:00:00", timezone)
|
||
|
||
// 时间计算
|
||
tomorrow := datetime.AddDays(now, 1)
|
||
startOfDay := datetime.StartOfDay(now, timezone)
|
||
```
|
||
|
||
### 场景7:数据库迁移(独立工具)⭐
|
||
|
||
```bash
|
||
# 1. 复制模板到项目
|
||
cp templates/migrate/main.go cmd/migrate/
|
||
|
||
# 2. 创建迁移文件 migrations/20240101000001_create_users.sql
|
||
|
||
# 3. 编译并使用
|
||
go build -o bin/migrate cmd/migrate/main.go
|
||
./bin/migrate up # 执行迁移
|
||
./bin/migrate status # 查看状态
|
||
```
|
||
|
||
**特点**:独立工具,零耦合,生产就绪
|
||
|
||
完整指南:[MIGRATION.md](./MIGRATION.md)
|
||
|
||
## 7. 更多文档
|
||
|
||
- [完整文档](./docs/README.md)
|
||
- [中间件文档](./docs/middleware.md)
|
||
- [工厂模式文档](./docs/factory.md)
|
||
- [HTTP工具文档](./docs/http.md)
|
||
- [配置文档](./docs/config.md)
|
||
|
||
## 常见问题
|
||
|
||
### Q: 如何自定义中间件配置?
|
||
|
||
查看 [中间件文档](./docs/middleware.md) 了解详细配置选项。
|
||
|
||
### Q: 如何使用数据库迁移?
|
||
|
||
查看 [迁移工具文档](./docs/migration.md) 了解数据库版本管理。
|
||
|
||
### Q: 支持哪些数据库?
|
||
|
||
支持 MySQL、PostgreSQL、SQLite。
|
||
|
||
### Q: 日志如何配置异步模式?
|
||
|
||
在配置文件中设置 `"async": true`,或通过代码配置:
|
||
|
||
```go
|
||
loggerConfig := &config.LoggerConfig{
|
||
Async: true,
|
||
BufferSize: 1000,
|
||
}
|
||
```
|
||
|
||
### Q: 如何按用户ID限流?
|
||
|
||
```go
|
||
limiter := middleware.NewTokenBucketLimiter(100, time.Minute)
|
||
rateLimitConfig := &middleware.RateLimitConfig{
|
||
Limiter: limiter,
|
||
KeyFunc: func(r *http.Request) string {
|
||
return r.Header.Get("X-User-ID")
|
||
},
|
||
}
|
||
chain := middleware.NewChain(
|
||
middleware.RateLimit(rateLimitConfig),
|
||
)
|
||
```
|
||
|
||
## 下一步
|
||
|
||
恭喜!你已经掌握了 GoCommon 的基本使用。
|
||
|
||
建议阅读:
|
||
1. [中间件文档](./docs/middleware.md) - 了解更多中间件配置
|
||
2. [工厂模式文档](./docs/factory.md) - 深入了解黑盒模式
|
||
3. [示例代码](./examples/) - 查看更多实际示例
|
||
|