feat: 添加配置、数据库及中间件包 #1

Merged
YingmoY merged 1 commit from feat/setup-base into main 2026-03-23 01:37:40 +08:00
YingmoY commented 2026-03-23 01:36:27 +08:00 (Migrated from github.com)
  • 在 internal/pkg/config/config.go 中使用 viper 实现配置管理
  • 在 internal/pkg/core/base_model.go 中为数据库实体创建基础模型结构
  • 在 internal/pkg/core/pagination.go 中添加了 PageQuery 和 PageResult 分页支持
  • 在 internal/pkg/core/response.go 中统一了 HTTP 处理器的响应结构
  • 在 internal/pkg/database/database.go 中建立了数据库连接与配置
  • 在 internal/pkg/ecode/ecode.go 中定义了统一的错误处理机制
  • 在 internal/pkg/logger/logger.go 中使用 zap 开发了日志功能
  • 在 internal/pkg/middleware/auth.go 中实现了 JWT 身份验证中间件
  • 在 internal/pkg/middleware/recovery.go 中添加了用于处理 panic 的恢复中间件
  • 在 internal/pkg/middleware/request_logger.go 中创建了请求日志记录中间件
  • 在 internal/pkg/mq/mq.go 中建立了用于消息队列的 RabbitMQ 客户端
  • 在 internal/router/router.go 中搭建了 API 路由结构
- 在 internal/pkg/config/config.go 中使用 viper 实现配置管理 - 在 internal/pkg/core/base_model.go 中为数据库实体创建基础模型结构 - 在 internal/pkg/core/pagination.go 中添加了 PageQuery 和 PageResult 分页支持 - 在 internal/pkg/core/response.go 中统一了 HTTP 处理器的响应结构 - 在 internal/pkg/database/database.go 中建立了数据库连接与配置 - 在 internal/pkg/ecode/ecode.go 中定义了统一的错误处理机制 - 在 internal/pkg/logger/logger.go 中使用 zap 开发了日志功能 - 在 internal/pkg/middleware/auth.go 中实现了 JWT 身份验证中间件 - 在 internal/pkg/middleware/recovery.go 中添加了用于处理 panic 的恢复中间件 - 在 internal/pkg/middleware/request_logger.go 中创建了请求日志记录中间件 - 在 internal/pkg/mq/mq.go 中建立了用于消息队列的 RabbitMQ 客户端 - 在 internal/router/router.go 中搭建了 API 路由结构
copilot-pull-request-reviewer[bot] (Migrated from github.com) reviewed 2026-03-23 01:39:55 +08:00
copilot-pull-request-reviewer[bot] (Migrated from github.com) left a comment

Pull request overview

该 PR 为 PharmacyERP 初始化服务端基础设施层能力(配置、日志、数据库、MQ、Gin 中间件与路由),并提供可运行的 cmd/server 入口,以便后续业务模块按约定注入路由。

Changes:

  • 引入统一配置加载(Viper + env 覆盖)与示例配置文件
  • 增加基础 core 能力:统一响应结构、分页结构、基础数据库模型
  • 建立服务启动骨架:Gin 路由、Zap 日志、GORM(Postgres) 连接、RabbitMQ 客户端与常用中间件(JWT/Recovery/RequestLogger)

Reviewed changes

Copilot reviewed 15 out of 17 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
cmd/server/main.go 服务启动入口:加载配置、初始化 logger/db/mq、启动 Gin HTTP Server 与优雅退出
internal/pkg/config/config.go Viper 配置加载、默认值与校验逻辑
internal/pkg/logger/logger.go Zap logger 初始化与输出格式/级别配置
internal/pkg/database/database.go GORM(Postgres) 初始化、连接池参数与关闭
internal/pkg/mq/mq.go RabbitMQ 客户端创建、队列声明、发布日志事件与关闭
internal/pkg/middleware/auth.go JWT 认证中间件、token 生成/解析与上下文取值辅助函数
internal/pkg/middleware/recovery.go Gin panic recovery 中间件:记录堆栈并返回统一错误响应
internal/pkg/middleware/request_logger.go Gin 请求日志中间件:记录耗时、状态码、UA 等
internal/router/router.go API 路由注册:healthz、NoRoute、模块化路由注入接口
internal/pkg/core/response.go 统一响应结构与 Success/Fail helper
internal/pkg/core/pagination.go PageQuery/PageResult 分页结构
internal/pkg/core/base_model.go GORM 基础模型字段定义
internal/pkg/ecode/ecode.go 统一业务错误码结构与预置错误
configs/config.example.yaml 配置示例文件
.gitignore 忽略本地 env 与本地配置文件
go.mod / go.sum 增加 Gin/GORM/Zap/Viper/JWT/RabbitMQ 等依赖与 toolchain 指令

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

## Pull request overview 该 PR 为 PharmacyERP 初始化服务端基础设施层能力(配置、日志、数据库、MQ、Gin 中间件与路由),并提供可运行的 `cmd/server` 入口,以便后续业务模块按约定注入路由。 **Changes:** - 引入统一配置加载(Viper + env 覆盖)与示例配置文件 - 增加基础 core 能力:统一响应结构、分页结构、基础数据库模型 - 建立服务启动骨架:Gin 路由、Zap 日志、GORM(Postgres) 连接、RabbitMQ 客户端与常用中间件(JWT/Recovery/RequestLogger) ### Reviewed changes Copilot reviewed 15 out of 17 changed files in this pull request and generated 7 comments. <details> <summary>Show a summary per file</summary> | File | Description | | ---- | ----------- | | `cmd/server/main.go` | 服务启动入口:加载配置、初始化 logger/db/mq、启动 Gin HTTP Server 与优雅退出 | | `internal/pkg/config/config.go` | Viper 配置加载、默认值与校验逻辑 | | `internal/pkg/logger/logger.go` | Zap logger 初始化与输出格式/级别配置 | | `internal/pkg/database/database.go` | GORM(Postgres) 初始化、连接池参数与关闭 | | `internal/pkg/mq/mq.go` | RabbitMQ 客户端创建、队列声明、发布日志事件与关闭 | | `internal/pkg/middleware/auth.go` | JWT 认证中间件、token 生成/解析与上下文取值辅助函数 | | `internal/pkg/middleware/recovery.go` | Gin panic recovery 中间件:记录堆栈并返回统一错误响应 | | `internal/pkg/middleware/request_logger.go` | Gin 请求日志中间件:记录耗时、状态码、UA 等 | | `internal/router/router.go` | API 路由注册:healthz、NoRoute、模块化路由注入接口 | | `internal/pkg/core/response.go` | 统一响应结构与 Success/Fail helper | | `internal/pkg/core/pagination.go` | PageQuery/PageResult 分页结构 | | `internal/pkg/core/base_model.go` | GORM 基础模型字段定义 | | `internal/pkg/ecode/ecode.go` | 统一业务错误码结构与预置错误 | | `configs/config.example.yaml` | 配置示例文件 | | `.gitignore` | 忽略本地 env 与本地配置文件 | | `go.mod` / `go.sum` | 增加 Gin/GORM/Zap/Viper/JWT/RabbitMQ 等依赖与 toolchain 指令 | </details> --- 💡 <a href="/YingmoY/PharmacyERP/new/main?filename=.github/instructions/*.instructions.md" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Add Copilot custom instructions</a> for smarter, more guided reviews. <a href="https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot" class="Link--inTextBlock" target="_blank" rel="noopener noreferrer">Learn how to get started</a>.
@ -0,0 +51,4 @@
if err := mqClient.Close(); err != nil {
log.Error("close rabbitmq failed", zap.Error(err))
}
}()
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:54 +08:00

mq.NewClient returns (nil, nil) when RabbitMQ is disabled, but this defer unconditionally calls mqClient.Close(). That will panic on shutdown when cfg.RabbitMQ.Enabled is false. Guard the defer with if mqClient != nil (or change NewClient to always return a non-nil no-op client when disabled).

	if mqClient != nil {
		defer func() {
			if err := mqClient.Close(); err != nil {
				log.Error("close rabbitmq failed", zap.Error(err))
			}
		}()
	}
mq.NewClient returns (nil, nil) when RabbitMQ is disabled, but this defer unconditionally calls mqClient.Close(). That will panic on shutdown when cfg.RabbitMQ.Enabled is false. Guard the defer with `if mqClient != nil` (or change NewClient to always return a non-nil no-op client when disabled). ```suggestion if mqClient != nil { defer func() { if err := mqClient.Close(); err != nil { log.Error("close rabbitmq failed", zap.Error(err)) } }() } ```
@ -4,0 +4,4 @@
toolchain go1.22.12
require (
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:54 +08:00

The toolchain go1.22.12 directive forces go to download/use that specific toolchain version, which can break builds in constrained CI environments or developer setups that pin a different toolchain. If the project doesn’t require a fixed toolchain, consider removing the toolchain directive (or aligning it with your CI/runtime expectations).


The `toolchain go1.22.12` directive forces `go` to download/use that specific toolchain version, which can break builds in constrained CI environments or developer setups that pin a different toolchain. If the project doesn’t require a fixed toolchain, consider removing the toolchain directive (or aligning it with your CI/runtime expectations). ```suggestion ```
@ -0,0 +164,4 @@
}
if c.RabbitMQ.Enabled && c.RabbitMQ.URI == "" {
return fmt.Errorf("rabbitmq.uri is required when rabbitmq is enabled")
}
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:54 +08:00

setDefaults() sets rabbitmq.enabled=true but does not set a default rabbitmq.uri, while validate() requires rabbitmq.uri when enabled. If a config file omits the rabbitmq section (or when relying on defaults/env), Load() will fail validation by default. Consider defaulting rabbitmq.enabled to false, or providing a sensible default URI for local dev, or relaxing validation unless the feature is explicitly enabled by the user.

setDefaults() sets rabbitmq.enabled=true but does not set a default rabbitmq.uri, while validate() requires rabbitmq.uri when enabled. If a config file omits the rabbitmq section (or when relying on defaults/env), Load() will fail validation by default. Consider defaulting rabbitmq.enabled to false, or providing a sensible default URI for local dev, or relaxing validation unless the feature is explicitly enabled by the user.
@ -0,0 +23,4 @@
Message: msg,
Data: nil,
})
}
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:53 +08:00

Fail() always responds with HTTP 200 even for auth failures and server errors. This makes errors indistinguishable at the HTTP layer (e.g., middleware.JWTAuth will return 200 on unauthorized) and is inconsistent with router.NoRoute which uses HTTP 404. Consider adding an HTTP status parameter (or mapping business codes to statuses) so callers can return 401/500/etc when appropriate.

func FailWithStatus(c *gin.Context, httpStatus int, code int, msg string) {
	c.JSON(httpStatus, Response{
		Code:    code,
		Message: msg,
		Data:    nil,
	})
}

func Fail(c *gin.Context, code int, msg string) {
	FailWithStatus(c, 200, code, msg)
}
Fail() always responds with HTTP 200 even for auth failures and server errors. This makes errors indistinguishable at the HTTP layer (e.g., middleware.JWTAuth will return 200 on unauthorized) and is inconsistent with router.NoRoute which uses HTTP 404. Consider adding an HTTP status parameter (or mapping business codes to statuses) so callers can return 401/500/etc when appropriate. ```suggestion func FailWithStatus(c *gin.Context, httpStatus int, code int, msg string) { c.JSON(httpStatus, Response{ Code: code, Message: msg, Data: nil, }) } func Fail(c *gin.Context, code int, msg string) { FailWithStatus(c, 200, code, msg) } ```
@ -0,0 +15,4 @@
zap.Any("panic", rec),
zap.ByteString("stack", debug.Stack()),
)
core.Fail(c, ecode.ErrSystem.Code, "system internal error")
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:54 +08:00

Recovery() hardcodes the error message "system internal error" even though ecode.ErrSystem already defines the canonical message. Using ecode.ErrSystem.Msg here avoids duplication and keeps responses consistent if the message changes.

		core.Fail(c, ecode.ErrSystem.Code, ecode.ErrSystem.Msg)
Recovery() hardcodes the error message "system internal error" even though ecode.ErrSystem already defines the canonical message. Using ecode.ErrSystem.Msg here avoids duplication and keeps responses consistent if the message changes. ```suggestion core.Fail(c, ecode.ErrSystem.Code, ecode.ErrSystem.Msg) ```
@ -0,0 +107,4 @@
return err
}
}
return nil
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:55 +08:00

Client.Close() returns immediately if channel.Close() fails, so the AMQP connection may never be closed and resources can leak. Consider attempting to close both channel and connection and returning a combined error (e.g., keep first error, or use multierr).

	var firstErr error
	if c.channel != nil {
		if err := c.channel.Close(); err != nil && firstErr == nil {
			firstErr = err
		}
	}
	if c.conn != nil {
		if err := c.conn.Close(); err != nil && firstErr == nil {
			firstErr = err
		}
	}
	return firstErr
Client.Close() returns immediately if channel.Close() fails, so the AMQP connection may never be closed and resources can leak. Consider attempting to close both channel and connection and returning a combined error (e.g., keep first error, or use multierr). ```suggestion var firstErr error if c.channel != nil { if err := c.channel.Close(); err != nil && firstErr == nil { firstErr = err } } if c.conn != nil { if err := c.conn.Close(); err != nil && firstErr == nil { firstErr = err } } return firstErr ```
@ -0,0 +22,4 @@
Code: http.StatusNotFound,
Message: "route not found",
Data: nil,
})
copilot-pull-request-reviewer[bot] (Migrated from github.com) commented 2026-03-23 01:39:53 +08:00

NoRoute manually constructs a core.Response and uses HTTP 404, while most other error responses go through core.Fail() (which currently always uses HTTP 200). To keep the API response contract consistent, consider routing NoRoute through the same response helper(s) and aligning the HTTP status strategy (either always 200 + business code, or use proper HTTP statuses everywhere).

		core.Fail(c, http.StatusNotFound, "route not found")
NoRoute manually constructs a core.Response and uses HTTP 404, while most other error responses go through core.Fail() (which currently always uses HTTP 200). To keep the API response contract consistent, consider routing NoRoute through the same response helper(s) and aligning the HTTP status strategy (either always 200 + business code, or use proper HTTP statuses everywhere). ```suggestion core.Fail(c, http.StatusNotFound, "route not found") ```
Sign in to join this conversation.
No description provided.