style(go): 合并连续变量声明并明确规范约束

This commit is contained in:
zhangdeman committed 2026-11-27 23:36:02 -08:00
1 parent 2492251a89
commit 5287321ca2
8 files changed
+42 -126

No files matched your search

+4 -12
View File
@@ -20,12 +20,8 @@ import (
func TestSQLObservationRedactsCredentials(t *testing.T) {
var (
core, logs = observer.New(zap.InfoLevel)
)
var (
logger = New(zap.New(core), "model_proxy")
)
var (
calls int
logger = New(zap.New(core), "model_proxy")
calls int
)
logger.Trace(context.Background(), time.Now(), func() (string, int64) { calls++; return "SELECT * FROM user WHERE id=7", 1 }, nil)
logger.Trace(context.Background(), time.Now(), func() (string, int64) { calls++; return "INSERT INTO user(password) VALUES ('private-value')", 0 }, errors.New("private-error"))
@@ -190,12 +186,8 @@ func TestSQLExecutionLogsOnce(t *testing.T) {
// TestRootLoggerAndNativeSessions 验证根配置、原生事务、LogMode 与并发会话隔离。
func TestRootLoggerAndNativeSessions(t *testing.T) {
var (
core, logs = observer.New(zap.InfoLevel)
)
var (
adapter = New(zap.New(core), "model_proxy")
)
var (
core, logs = observer.New(zap.InfoLevel)
adapter = New(zap.New(core), "model_proxy")
database, err = gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: adapter})
)
if err != nil {
+1 -1
View File
@@ -28,7 +28,7 @@
## 3. Go 编码与公开契约
- 使用 gofmt;包名小写,命名表达职责。导出名称避免重复包名前缀;Gin 上下文参数优先命名 ctx。
- 显式 var 声明使用声明块;同一作用域连续声明尽量合并,保留求值顺序和作用域,不机械改写 :=。
- 显式 var 声明必须使用 `var (...)` 声明块;同一作用域内连续的 var 声明必须合并为一个声明块,禁止为每个变量分别创建连续的 var 块。合并时必须保留变量声明顺序、初始化求值顺序和作用域,不跨越执行语句合并,不机械改写 `:=`。
- 单个函数固定参数不超过四个;职责清晰的流程保持完整,不为减少行数提取无意义转发函数。
- 优先明确结构体和类型。any 只用于路由 DTO、日志副本、原生适配等真实异构边界,并在注释或字段说明中说明用途。
- 所有包级导出声明应有以标识符开头的 godoc 注释。函数和方法说明用途、入参、返回和错误语义;涉及资源或状态的说明副作用。
+4 -12
View File
@@ -18,18 +18,10 @@ import (
func New(t *testing.T, protocol int) *redis.Client {
var (
server, err = exec.LookPath("redis-server")
)
var (
directory string
)
var (
command *exec.Cmd
)
var (
client *redis.Client
)
var (
deadline time.Time
directory string
command *exec.Cmd
client *redis.Client
deadline time.Time
)
t.Helper()
if err != nil {
+11 -33
View File
@@ -49,9 +49,7 @@ var (
// 返回:只供写日志的 Zap 实例,调用方不得关闭。
func Instance(name string) *zap.Logger {
var (
item output
)
var (
item output
exists bool
)
outputMutex.RLock()
@@ -68,30 +66,14 @@ func Instance(name string) *zap.Logger {
// 返回:已发布实例;失败返回带内部场景码及原因链的错误,不修改活动实例。
func ConfigureOutput(cfg *OutputConfig) (*zap.Logger, error) {
var (
writer *rotatelogs.RotateLogs
)
var (
err error
)
var (
pattern string
)
var (
interval time.Duration
)
var (
cores []zapcore.Core
)
var (
options []zap.Option
)
var (
level = zapcore.InfoLevel
)
var (
maxAge = int64(3 * 24 * 3600)
)
var (
writer *rotatelogs.RotateLogs
err error
pattern string
interval time.Duration
cores []zapcore.Core
options []zap.Option
level = zapcore.InfoLevel
maxAge = int64(3 * 24 * 3600)
name, division string
)
outputMutex.Lock()
@@ -190,12 +172,8 @@ func (cfg *OutputConfig) encoder() zapcore.Encoder {
func outputTime(value time.Time, encoder zapcore.PrimitiveArrayEncoder) {
var (
second = value.UnixNano() / 1e9
)
var (
milli = value.UnixNano() / 1e6 % 1e3
)
var (
nano = value.UnixNano() % 1e6
milli = value.UnixNano() / 1e6 % 1e3
nano = value.UnixNano() % 1e6
)
encoder.AppendString(time.Unix(second, nano).Format(time.DateTime) + "." + fmt.Sprint(milli) + "+" + fmt.Sprint(nano))
}
+2 -6
View File
@@ -38,12 +38,8 @@ func Safe(value any) any { return safe(value, 0) }
func safe(value any, depth int) any {
var (
target any
)
var (
data []byte
)
var (
err error
data []byte
err error
)
if depth > 16 {
return "[MAX DEPTH]"
+1 -5
View File
@@ -15,11 +15,7 @@ func TestCredentialCopiesPreserveOriginalAndNumbers(t *testing.T) {
"apiKey": "private-api",
"nested": `{"accessKey":"private-access","id":18446744073709551615}`,
}
)
var (
result = Safe(original)
)
var (
result = Safe(original)
body, err = json.Marshal(result)
)
if err != nil {
+11 -33
View File
@@ -46,9 +46,7 @@ func (h *Hook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
var (
begin = time.Now()
)
var (
err = next(ctx, cmd)
err = next(ctx, cmd)
)
h.record(ctx, cmd, time.Since(begin), err)
return err
@@ -61,12 +59,8 @@ func (h *Hook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
func (h *Hook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return func(ctx context.Context, cmds []redis.Cmder) error {
var (
begin = time.Now()
)
var (
err = next(ctx, cmds)
)
var (
begin = time.Now()
err = next(ctx, cmds)
elapsed = time.Since(begin)
)
for _, cmd := range cmds {
@@ -80,31 +74,15 @@ func (h *Hook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.Process
// 入参:ctx 为可信诊断上下文,cmd 为原生命令,elapsed 为执行耗时,resultErr 为当前命令真实结果。
func (h *Hook) record(ctx context.Context, cmd redis.Cmder, elapsed time.Duration, resultErr error) {
var (
args = cmd.Args()
)
var (
result any
)
var (
args = cmd.Args()
result any
loggedArgs any
)
var (
hidden bool
)
var (
status = "success"
)
var (
name = strings.ToLower(cmd.Name())
)
var (
method reflect.Value
)
var (
values []reflect.Value
)
var (
fields []zap.Field
hidden bool
status = "success"
name = strings.ToLower(cmd.Name())
method reflect.Value
values []reflect.Value
fields []zap.Field
)
if h.logger == nil {
return
+8 -24
View File
@@ -17,16 +17,10 @@ import (
// TestNativePipelineObservationPreservesData 验证 Pipeline 逐条对应记录,日志脱敏不修改执行参数和返回正文。
func TestNativePipelineObservationPreservesData(t *testing.T) {
var (
client = redisserver.New(t, 3)
)
var (
client = redisserver.New(t, 3)
core, logs = observer.New(zap.InfoLevel)
)
var (
ctx = context.Background()
)
var (
value = `{"nested":{"token":"private-token"},"data":"kept"}`
ctx = context.Background()
value = `{"nested":{"token":"private-token"},"data":"kept"}`
)
client.AddHook(New(zap.New(core), "cache"))
var (
@@ -34,9 +28,7 @@ func TestNativePipelineObservationPreservesData(t *testing.T) {
)
pipeline.Set(ctx, "safe-key", value, 0)
var (
get = pipeline.Get(ctx, "safe-key")
)
var (
get = pipeline.Get(ctx, "safe-key")
missing = pipeline.Get(ctx, "missing-key")
)
if _, err := pipeline.Exec(ctx); !errors.Is(err, redis.Nil) {
@@ -71,18 +63,10 @@ func TestNativePipelineObservationPreservesData(t *testing.T) {
func TestHookObservesReturnedError(t *testing.T) {
var (
core, logs = observer.New(zap.InfoLevel)
)
var (
hook = New(zap.New(core), "cache")
)
var (
cmd = redis.NewStringCmd(context.Background(), "get", "safe-key")
)
var (
calls int
)
var (
process = hook.ProcessHook(func(context.Context, redis.Cmder) error { calls++; return context.Canceled })
hook = New(zap.New(core), "cache")
cmd = redis.NewStringCmd(context.Background(), "get", "safe-key")
calls int
process = hook.ProcessHook(func(context.Context, redis.Cmder) error { calls++; return context.Canceled })
)
if err := process(context.Background(), cmd); !errors.Is(err, context.Canceled) {
t.Fatalf("error changed: %v", err)
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.