Files
go-common/QUICKSTART.md
2025-12-05 00:07:15 +08:00

347 lines
7.0 KiB
Markdown
Raw Permalink 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.

# 快速开始指南
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
},
"rateLimit": {
"enable": true,
"rate": 100,
"period": 60,
"byIP": 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)
}
// 使用factory的黑盒方法获取中间件链
// 自动从配置文件读取并配置所有中间件
chain := fac.GetMiddlewareChain()
// (可选)如果项目需要额外的中间件,可以继续添加
// chain.Append(yourAuthMiddleware, yourMetricsMiddleware)
// 注册路由
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: 如何添加自定义中间件?
```go
// 获取基础中间件链
chain := fac.GetMiddlewareChain()
// 添加自定义中间件
chain.Append(
yourAuthMiddleware, // 认证中间件
yourMetricsMiddleware, // 指标中间件
// 更多自定义中间件...
)
// 使用扩展后的中间件链
http.Handle("/api/secure", chain.ThenFunc(yourHandler))
```
自定义中间件示例:
```go
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "Unauthorized", 401)
return
}
// 验证token...
next.ServeHTTP(w, r)
})
}
```
### Q: 如何按用户ID限流
在配置文件中设置:
```json
{
"rateLimit": {
"enable": true,
"rate": 100,
"period": 60,
"byUserID": true,
"byIP": false
}
}
```
中间件会自动从 `X-User-ID` header 中获取用户ID进行限流。
## 下一步
恭喜!你已经掌握了 GoCommon 的基本使用。
建议阅读:
1. [中间件文档](./docs/middleware.md) - 了解更多中间件配置
2. [工厂模式文档](./docs/factory.md) - 深入了解黑盒模式
3. [示例代码](./examples/) - 查看更多实际示例