Skip to content

Commit 5f85b59

Browse files
authored
Merge pull request #1 from sunjunnan79/fix_gin
feat:gin部分拆分
2 parents a6b2df4 + 4c70671 commit 5f85b59

15 files changed

Lines changed: 401 additions & 478 deletions

File tree

example/logger/logger.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ package main
22

33
import (
44
"errors"
5+
"github.com/muxi-Infra/muxi-micro/pkg/1"
6+
"github.com/muxi-Infra/muxi-micro/pkg/1/zapx"
57
"github.com/muxi-Infra/muxi-micro/pkg/errs"
6-
"github.com/muxi-Infra/muxi-micro/pkg/logger"
7-
"github.com/muxi-Infra/muxi-micro/pkg/logger/zapx"
88
)
99

1010
var DBNOData = errs.NewErr("db_no_data", "db has no data")

pkg/logger/logger.go

Lines changed: 1 addition & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,59 +10,4 @@ type Logger interface {
1010
Sync() error
1111
}
1212

13-
type Field struct {
14-
Key string
15-
Val any
16-
}
17-
18-
func Any(key string, val any) Field {
19-
return Field{
20-
Key: key,
21-
Val: val,
22-
}
23-
}
24-
25-
func Error(err error) Field {
26-
return Field{
27-
Key: "error",
28-
Val: err,
29-
}
30-
}
31-
32-
func Int64(key string, val int64) Field {
33-
return Field{
34-
Key: key,
35-
Val: val,
36-
}
37-
}
38-
39-
func Int(key string, val int) Field {
40-
return Field{
41-
Key: key,
42-
Val: val,
43-
}
44-
}
45-
46-
func String(key string, val string) Field {
47-
return Field{
48-
Key: key,
49-
Val: val,
50-
}
51-
}
52-
53-
func Int32(key string, val int32) Field {
54-
return Field{
55-
Key: key,
56-
Val: val,
57-
}
58-
}
59-
60-
// ---------- 环境枚举 ----------
61-
type Env int8
62-
63-
const (
64-
EnvUnknown Env = iota
65-
EnvDev // 开发:彩色多行栈,仅控制台
66-
EnvTest // 测试:彩色多行栈到控制台 + JSON 到文件
67-
EnvProd // 生产:全 JSON 单行
68-
)
13+
type Field map[string]interface{}

pkg/logger/zapx/zapx.go

Lines changed: 24 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ package zapx
33
import (
44
"fmt"
55
"github.com/muxi-Infra/muxi-micro/pkg/logger"
6+
"github.com/muxi-Infra/muxi-micro/static"
67
"go.uber.org/zap"
78
"go.uber.org/zap/zapcore"
89
"gopkg.in/natefinch/lumberjack.v2"
910
"log"
1011
"os"
1112
"path/filepath"
12-
"strings"
1313
)
1414

1515
type ZapLogger struct{ l *zap.Logger }
@@ -21,7 +21,7 @@ type ZapCfg struct {
2121
options []zap.Option
2222
}
2323

24-
func NewDefaultZapLogger(logDir string, env logger.Env) logger.Logger {
24+
func NewDefaultZapLogger(logDir string, env static.Env) logger.Logger {
2525
return NewZapLogger(
2626
WithDefaultZapCore(
2727
WithLogDir(logDir),
@@ -45,23 +45,16 @@ func NewZapLogger(opts ...ZapOption) logger.Logger {
4545
type CoreOption func(*coreCfg)
4646

4747
type coreCfg struct {
48-
env logger.Env
49-
splitByLevel bool
50-
logDir string
48+
env static.Env
49+
logDir string
5150
}
5251

53-
func WithCoreEnv(env logger.Env) CoreOption {
52+
func WithCoreEnv(env static.Env) CoreOption {
5453
return func(cfg *coreCfg) {
5554
cfg.env = env
5655
}
5756
}
5857

59-
func WithCoreSplit(splitByLevel bool) CoreOption {
60-
return func(cfg *coreCfg) {
61-
cfg.splitByLevel = splitByLevel
62-
}
63-
}
64-
6558
func WithLogDir(logDir string) CoreOption {
6659
return func(cfg *coreCfg) {
6760
cfg.logDir = logDir
@@ -71,16 +64,15 @@ func WithLogDir(logDir string) CoreOption {
7164
func WithDefaultZapCore(opts ...CoreOption) ZapOption {
7265
return func(cfg *ZapCfg) {
7366
var corecfg = coreCfg{
74-
splitByLevel: false,
75-
logDir: "./logs",
76-
env: logger.EnvProd,
67+
logDir: "./logs",
68+
env: static.EnvProd,
7769
}
7870

7971
for _, opt := range opts {
8072
opt(&corecfg)
8173
}
8274
// dev 只需要 stdout,不强制创建 logDir
83-
if corecfg.env != logger.EnvDev {
75+
if corecfg.env != static.EnvDev {
8476
corecfg.logDir = filepath.Clean(corecfg.logDir)
8577
if err := os.MkdirAll(corecfg.logDir, 0755); err != nil {
8678
log.Panicf("无法创建日志目录: %v", err)
@@ -92,20 +84,20 @@ func WithDefaultZapCore(opts ...CoreOption) ZapOption {
9284

9385
switch corecfg.env {
9486
// ======== DEV:彩色到控制台 ========
95-
case logger.EnvDev:
87+
case static.EnvDev:
9688
cfg.core = zapcore.NewCore(consoleEnc, zapcore.AddSync(os.Stdout), zapcore.DebugLevel)
9789
return
9890

9991
// ======== TEST:控制台彩色 + 文件 JSON ========
100-
case logger.EnvTest:
92+
case static.EnvTest:
10193
consoleCore := zapcore.NewCore(consoleEnc, zapcore.AddSync(os.Stdout), zapcore.DebugLevel)
102-
fileCore := buildFileCores(jsonEnc, corecfg.splitByLevel, corecfg.logDir, false) // 仅文件
94+
fileCore := buildFileCores(jsonEnc, corecfg.logDir, false) // 仅文件
10395
cfg.core = zapcore.NewTee(append([]zapcore.Core{consoleCore}, fileCore...)...)
10496
return
10597

10698
// ======== PROD(默认):全 JSON 单行 ========
107-
case logger.EnvProd:
108-
cores := buildFileCores(jsonEnc, corecfg.splitByLevel, corecfg.logDir, true) // stdout+file 共写
99+
case static.EnvProd:
100+
cores := buildFileCores(jsonEnc, corecfg.logDir, true) // stdout+file 共写
109101
cfg.core = zapcore.NewTee(cores...)
110102

111103
default:
@@ -137,36 +129,17 @@ func WithZapCore(core zapcore.Core) ZapOption {
137129
}
138130

139131
// 构造文件相关 core;如果 withStdout=true,则 stdout 也走同 encoder(生产)
140-
func buildFileCores(enc zapcore.Encoder, split bool, dir string, withStdout bool) []zapcore.Core {
132+
func buildFileCores(enc zapcore.Encoder, dir string, withStdout bool) []zapcore.Core {
141133
var cores []zapcore.Core
142134
stdout := zapcore.AddSync(os.Stdout)
143135

144-
if !split {
145-
var ws zapcore.WriteSyncer
146-
if withStdout {
147-
ws = zapcore.NewMultiWriteSyncer(stdout, zapcore.AddSync(newRotateLogger(fmt.Sprintf("%s/app.log", dir))))
148-
} else {
149-
ws = zapcore.AddSync(newRotateLogger(fmt.Sprintf("%s/app.log", dir)))
150-
}
151-
cores = append(cores, zapcore.NewCore(enc, ws, zapcore.DebugLevel))
152-
return cores
153-
}
154-
155-
levels := []zapcore.Level{
156-
zapcore.DebugLevel, zapcore.InfoLevel, zapcore.WarnLevel,
157-
zapcore.ErrorLevel, zapcore.DPanicLevel, zapcore.PanicLevel, zapcore.FatalLevel,
158-
}
159-
for _, lv := range levels {
160-
fileWS := zapcore.AddSync(newRotateLogger(fmt.Sprintf("%s/%s.log", dir, strings.ToLower(lv.String()))))
161-
var ws zapcore.WriteSyncer
162-
if withStdout {
163-
ws = zapcore.NewMultiWriteSyncer(stdout, fileWS)
164-
} else {
165-
ws = fileWS
166-
}
167-
core := zapcore.NewCore(enc, ws, zap.LevelEnablerFunc(func(l zapcore.Level) bool { return l == lv }))
168-
cores = append(cores, core)
136+
var ws zapcore.WriteSyncer
137+
if withStdout {
138+
ws = zapcore.NewMultiWriteSyncer(stdout, zapcore.AddSync(newRotateLogger(fmt.Sprintf("%s/app.log", dir))))
139+
} else {
140+
ws = zapcore.AddSync(newRotateLogger(fmt.Sprintf("%s/app.log", dir)))
169141
}
142+
cores = append(cores, zapcore.NewCore(enc, ws, zapcore.DebugLevel))
170143
return cores
171144
}
172145

@@ -220,8 +193,10 @@ func (z *ZapLogger) Sync() error { return z.l.Sync() }
220193

221194
func convert(fields []logger.Field) []zap.Field {
222195
var res []zap.Field
223-
for _, arg := range fields {
224-
res = append(res, zap.Any(arg.Key, arg.Val))
196+
for _, f := range fields {
197+
for k, v := range f {
198+
res = append(res, zap.Any(k, v))
199+
}
225200
}
226201
return res
227202
}

pkg/logger/zapx/zapx_test.go

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
package zapx
22

33
import (
4-
"errors"
54
"fmt"
6-
"os"
7-
"path/filepath"
8-
"testing"
9-
105
"github.com/muxi-Infra/muxi-micro/pkg/logger"
6+
"github.com/muxi-Infra/muxi-micro/static"
117
"go.uber.org/zap"
128
"go.uber.org/zap/zapcore"
9+
"os"
10+
"path/filepath"
11+
"testing"
1312
)
1413

1514
func TestNewDefaultZapLogger_AllEnv(t *testing.T) {
16-
envs := []logger.Env{logger.EnvDev, logger.EnvTest, logger.EnvProd}
15+
envs := []static.Env{static.EnvDev, static.EnvTest, static.EnvProd}
1716
for _, env := range envs {
1817
t.Run(fmt.Sprintf("%v", env), func(t *testing.T) {
1918
l := NewDefaultZapLogger("./logs/test_default", env)
@@ -74,8 +73,7 @@ func TestWithDefaultZapCore_CreatesLogDir(t *testing.T) {
7473
_ = os.RemoveAll(dir)
7574

7675
opt := WithDefaultZapCore(
77-
WithCoreEnv(logger.EnvTest),
78-
WithCoreSplit(false),
76+
WithCoreEnv(static.EnvTest),
7977
WithLogDir(dir),
8078
)
8179
cfg := &ZapCfg{}
@@ -93,7 +91,7 @@ func TestWithDefaultZapCore_IllegalEnv(t *testing.T) {
9391
}
9492
}()
9593

96-
opt := WithDefaultZapCore(WithCoreSplit(true), WithLogDir("./logs/illegal"), WithCoreEnv(logger.Env(99)))
94+
opt := WithDefaultZapCore(WithLogDir("./logs/illegal"), WithCoreEnv(static.Env(99)))
9795
cfg := &ZapCfg{}
9896
opt(cfg)
9997
}
@@ -126,7 +124,7 @@ func TestWithZapOptions_AppendsOptions(t *testing.T) {
126124
func TestLogDirClean(t *testing.T) {
127125
// 测试 logDir clean 是否去除末尾斜杠
128126
logDir := "./logs/clean-test////"
129-
opt := WithDefaultZapCore(WithCoreSplit(true), WithLogDir(logDir), WithCoreEnv(logger.EnvTest))
127+
opt := WithDefaultZapCore(WithLogDir(logDir), WithCoreEnv(static.EnvTest))
130128
cfg := &ZapCfg{}
131129
opt(cfg)
132130

@@ -138,17 +136,20 @@ func TestLogDirClean(t *testing.T) {
138136

139137
func logAll(l logger.Logger) {
140138

141-
l.With(logger.String("all", "everyLog"))
139+
l.With(logger.Field{
140+
"string": "string",
141+
"int": 1,
142+
})
143+
142144
l.Info("test",
143-
logger.Int("1", 1),
144-
logger.Int32("1", 1),
145-
logger.Int64("1", 1),
146-
logger.Any("1", 1),
147-
logger.Error(errors.New("1234")),
145+
logger.Field{
146+
"string": "string",
147+
"int": 1,
148+
},
148149
)
149150

150-
l.Debug("test", logger.Int("1", 1))
151-
l.Warn("test", logger.Int("1", 1))
152-
l.Error("test", logger.Int("1", 1))
151+
l.Debug("test")
152+
l.Warn("test")
153+
l.Error("test")
153154
l.Sync()
154155
}

pkg/transport/http/ginx/engine.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package ginx
2+
3+
import (
4+
"github.com/gin-contrib/pprof"
5+
"github.com/gin-gonic/gin"
6+
"github.com/muxi-Infra/muxi-micro/pkg/logger"
7+
"github.com/muxi-Infra/muxi-micro/pkg/logger/zapx"
8+
"github.com/muxi-Infra/muxi-micro/pkg/transport/http/ginx/middleware/cors"
9+
"github.com/muxi-Infra/muxi-micro/pkg/transport/http/ginx/middleware/limiter"
10+
"github.com/muxi-Infra/muxi-micro/pkg/transport/http/ginx/middleware/timeout"
11+
"github.com/muxi-Infra/muxi-micro/static"
12+
)
13+
14+
type engineConfig struct {
15+
env static.Env
16+
g *gin.Engine
17+
l logger.Logger
18+
name string
19+
}
20+
21+
type EngineOption func(*engineConfig)
22+
23+
// 设置服务名称
24+
func WithEnv(env static.Env) EngineOption {
25+
return func(cfg *engineConfig) {
26+
cfg.env = env
27+
}
28+
}
29+
30+
// 手动控制gin的Engine
31+
func WithEngine(g *gin.Engine) EngineOption {
32+
return func(cfg *engineConfig) {
33+
cfg.g = g
34+
}
35+
}
36+
37+
func WithName(name string) EngineOption {
38+
return func(cfg *engineConfig) {
39+
cfg.name = name
40+
}
41+
}
42+
func WithLogger(l logger.Logger) EngineOption {
43+
return func(cfg *engineConfig) {
44+
cfg.l = l
45+
}
46+
}
47+
48+
// 创建默认引擎,附带常用中间件和可选配置
49+
func NewDefaultEngine(opts ...EngineOption) *gin.Engine {
50+
cfg := &engineConfig{
51+
env: static.EnvProd,
52+
g: gin.Default(),
53+
name: DefaultName,
54+
l: zapx.NewZapLogger(zapx.WithDefaultZapCore()), //如果不配置logger的话就默认使用zap
55+
}
56+
57+
for _, opt := range opts {
58+
opt(cfg)
59+
}
60+
61+
// 非生产环境注册 pprof
62+
if cfg.env != static.EnvProd {
63+
pprof.Register(cfg.g)
64+
}
65+
66+
cfg.g.Use(
67+
GlobalLoggerMiddleware(cfg.l),
68+
GlobalNameMiddleware(cfg.name),
69+
)
70+
71+
return cfg.g
72+
}
73+
74+
func UseDefaultMiddleware(g *gin.Engine) {
75+
g.Use(
76+
cors.Cors(),
77+
limiter.Limiter(),
78+
timeout.Timeout(),
79+
)
80+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package ginx

0 commit comments

Comments
 (0)