# 快速开始指南 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"}, "测试邮件", "纯文本内容", "