Skip to content

Commit f54cbbc

Browse files
author
w7years
committed
🔧 chore(config): update server port and max request body size in config.yaml
📝 fix(main.go): improve error messages and logging for configuration loading 🐳 chore(Dockerfile): update environment variables and improve documentation 📝 refactor(reverse_proxy.go): improve logging for request processing and handle errors 🔒 fix(middleware.go): enhance security headers and improve comments 🔍 fix(config.go): refine error messages and improve config loading logic 📝 refactor(logger.go): update logger initialization to return errors instead of panicking
1 parent 15908c6 commit f54cbbc

File tree

8 files changed

+97
-92
lines changed

8 files changed

+97
-92
lines changed

Dockerfile

+15-15
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,48 @@
1-
# 构建阶段
1+
# Build stage
22
FROM golang:1.23.2-alpine AS builder
33

4-
# 设置工作目录
4+
# Set working directory
55
WORKDIR /app
66

7-
# 复制 go.mod go.sum 并下载依赖
7+
# Copy go.mod and go.sum and download dependencies
88
COPY go.mod go.sum ./
99
RUN go mod download
1010

11-
# 复制源代码并构建
11+
# Copy source code and build
1212
COPY . .
1313
RUN CGO_ENABLED=0 GOOS=linux go build -o proxy ./cmd/proxy
1414

15-
# 运行阶段
15+
# Run stage
1616
FROM alpine:latest
1717

18-
# 安装证书
18+
# Install certificates
1919
RUN apk --no-cache add ca-certificates tzdata
2020

21-
# 设置默认时区为上海
21+
# Set default timezone to Shanghai
2222
ENV TZ=Asia/Shanghai
2323

24-
# 设置工作目录
24+
# Set working directory
2525
WORKDIR /app
2626

27-
# 创建日志目录并设置权限
27+
# Create logs directory and set permissions
2828
RUN mkdir -p /app/logs && chmod 755 /app/logs
2929

30-
# 复制可执行文件
30+
# Copy executable file
3131
COPY --from=builder /app/proxy .
3232
COPY --from=builder /app/config.yaml .
3333

34-
# 设置环境变量,指定默认配置文件路径
34+
# Set environment variables, specify default config file path
3535
ENV CONFIG_PATH=/app/config.yaml
3636
ENV PORT=3002
3737

38-
# 复制入口脚本
38+
# Copy entrypoint script
3939
COPY entrypoint.sh /app/entrypoint.sh
4040
RUN chmod +x /app/entrypoint.sh
4141

42-
# 设置时区
42+
# Set timezone
4343
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
4444

4545
EXPOSE $PORT
4646

47-
# 设置入口点
48-
ENTRYPOINT ["/app/entrypoint.sh"]
47+
# Set entrypoint
48+
ENTRYPOINT ["/app/entrypoint.sh"]

cmd/proxy/main.go

+29-27
Original file line numberDiff line numberDiff line change
@@ -26,98 +26,100 @@ func main() {
2626
configPath := flag.String("config", "config.yaml", "配置文件路径")
2727
flag.Parse()
2828

29-
// 加载配置
29+
// Load config
3030
cfg, err := config.LoadConfig(*configPath)
3131
if err != nil {
32-
log.Fatalf("加载配置失败: %v", err)
32+
log.Fatalf("Load config failed: %v", err)
3333
}
3434

35-
// 初始化日志
36-
logger.InitLogger(cfg)
35+
// Initialize logger
36+
err = logger.InitLogger(cfg)
37+
if err != nil {
38+
log.Fatalf("Init logger failed: %v", err)
39+
}
3740

38-
// 设置限流
41+
// Set up rate limiting
3942
rate, err := limiter.NewRateFromFormatted(cfg.RateLimit)
4043
if err != nil {
41-
logger.Logger.Fatalf("限流配置错误: %v", err)
44+
logger.Logger.Fatalf("Rate limiting config error: %v", err)
4245
}
4346
store := memory.NewStore()
4447
instance := limiter.New(store, rate)
4548
limiterMiddleware := ginmiddleware.NewMiddleware(instance)
4649

47-
// 设置 GIN Release 模式
50+
// Set GIN to Release mode
4851
gin.SetMode(gin.ReleaseMode)
4952

50-
// 初始化 Gin 路由
53+
// Initialize Gin router
5154
router := gin.New()
52-
// 添加健康检查路由
55+
// Add health check route
5356
router.GET("/generate_204", func(c *gin.Context) {
5457
logger.Logger.Debugln("generate_204 success.")
5558
c.Status(http.StatusNoContent)
5659
})
5760

58-
// 初始化代理
61+
// Initialize proxy
5962
openAIProxy, err := proxy.NewOpenAIReverseProxy(cfg)
6063
if err != nil {
61-
logger.Logger.Fatalf("初始化代理失败: %v", err)
64+
logger.Logger.Fatalf("Initialize proxy failed: %v", err)
6265
}
6366

64-
// 应用限流中间件
67+
// Apply rate limiting middleware
6568
apiGroup := router.Group("/")
6669
apiGroup.Use(middleware.APIKeyAuthMiddleware())
6770
apiGroup.Use(limiterMiddleware)
6871
apiGroup.Use(middleware.SecurityHeadersMiddleware())
6972
apiGroup.Use(middleware.LimitRequestBody(int64(cfg.MaxRequestBodySizeMB << 20)))
70-
//router.Use(middleware.ContentTypeMiddleware(logger.Logger))
7173

7274
for prefix := range cfg.PathMap {
7375
apiGroup.Any(prefix+"/*path", func(c *gin.Context) {
7476
openAIProxy.ServeHTTP(c.Writer, c.Request)
7577
})
7678
}
7779

78-
// 在主路由器上设置 NoRoute 处理程序
80+
// Set NoRoute handler on main router
7981
router.NoRoute(func(c *gin.Context) {
80-
middleware.ErrorHandler(c.Writer, fmt.Sprintf("未知的路径: %s", c.Request.URL.Path), http.StatusNotFound)
82+
middleware.ErrorHandler(c.Writer, fmt.Sprintf("Unknown path: %s", c.Request.URL.Path), http.StatusNotFound)
8183
})
8284

83-
// 设置服务器
85+
// Set up server
8486
srv := &http.Server{
8587
Addr: ":" + cfg.ServerPort,
8688
Handler: router,
87-
ReadTimeout: 10 * time.Second,
88-
WriteTimeout: 10 * time.Second,
89+
ReadTimeout: 90 * time.Second,
90+
WriteTimeout: 90 * time.Second,
8991
IdleTimeout: 120 * time.Second,
9092
}
9193

9294
errChan := make(chan error, 1)
9395

94-
// 等待中断信号
96+
// Wait for interrupt signal
9597
quit := make(chan os.Signal, 1)
9698
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
9799

98-
// 启动服务器
100+
// Start server
99101
go func() {
100102
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
101-
logger.Logger.Fatalf("无法启动服务器: %v", err)
103+
logger.Logger.Fatalf("Failed to start server: %v", err)
102104
errChan <- err
103105
} else {
104-
logger.Logger.Infof("服务启动成功:%s", cfg.ServerPort)
106+
logger.Logger.Infof("Server started successfully: %s", cfg.ServerPort)
105107
}
106108
}()
107109

108110
select {
109111
case <-quit:
110-
logger.Logger.Info("收到关闭信号,正在关闭服务器...")
112+
logger.Logger.Info("Received shutdown signal, shutting down server...")
111113
case err := <-errChan:
112-
logger.Logger.Errorf("服务器运行时发生错误: %v", err)
114+
logger.Logger.Errorf("Server error: %v", err)
113115
quit <- syscall.SIGINT
114116
}
115117

116-
// 优雅关闭
118+
// Graceful shutdown
117119
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
118120
defer cancel()
119121
if err := srv.Shutdown(ctx); err != nil {
120-
logger.Logger.Fatalf("服务器关闭失败: %v", err)
122+
logger.Logger.Fatalf("Server shutdown failed: %v", err)
121123
}
122-
logger.Logger.Info("服务器已关闭")
124+
logger.Logger.Info("Server shutdown")
123125
}

config.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
server_port: "3001"
1+
server_port: "3002"
22
rate_limit: "100-M"
33
fixed_request_ip: ""
4-
max_request_body_size_mb: 50
4+
max_request_body_size_mb: 100
55
log_dir: "logs"
66
log_name: "app.log"
77
log_level: "info"

go.mod

-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ require (
88
github.com/spf13/viper v1.19.0
99
github.com/stretchr/testify v1.9.0
1010
github.com/ulule/limiter/v3 v3.11.2
11-
go.uber.org/zap v1.27.0
1211
)
1312

1413
require (

internal/config/config.go

+7-6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"github.com/spf13/viper"
77
)
88

9+
// Config config struct
910
type Config struct {
1011
ServerPort string `mapstructure:"server_port"`
1112
RateLimit string `mapstructure:"rate_limit"`
@@ -17,30 +18,30 @@ type Config struct {
1718
PathMap map[string]string `mapstructure:"path_map"`
1819
}
1920

20-
// LoadConfig 配置加载
21+
// LoadConfig load config
2122
func LoadConfig(configPath string) (*Config, error) {
2223
viper.SetConfigType("yaml")
2324
viper.SetConfigFile(configPath)
2425

25-
// 设置默认值
26+
// Set default values
2627
viper.SetDefault("server_port", "3001")
2728
viper.SetDefault("rate_limit", "100-M")
28-
viper.SetDefault("max_request_body_size_mb", "20")
29+
viper.SetDefault("max_request_body_size_mb", "100")
2930
viper.SetDefault("log_dir", "logs")
3031
viper.SetDefault("log_name", "app.log")
3132
viper.SetDefault("log_level", "info")
3233

3334
if err := viper.ReadInConfig(); err != nil {
34-
return nil, fmt.Errorf("读取配置文件时发生错误: %v", err)
35+
return nil, fmt.Errorf("read config file failed: %v", err)
3536
}
3637

3738
var cfg Config
3839
if err := viper.Unmarshal(&cfg); err != nil {
39-
return nil, fmt.Errorf("无法解析配置: %v", err)
40+
return nil, fmt.Errorf("unmarshal config failed: %v", err)
4041
}
4142

4243
if len(cfg.PathMap) == 0 {
43-
return nil, fmt.Errorf("路径映射配置为空")
44+
return nil, fmt.Errorf("path map config is empty")
4445
}
4546

4647
return &cfg, nil

internal/middleware/middleware.go

+9-9
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"github.com/gin-gonic/gin"
99
)
1010

11-
// APIKeyAuthMiddleware 验证请求中的 API 密钥
11+
// APIKeyAuthMiddleware verify api key
1212
func APIKeyAuthMiddleware() gin.HandlerFunc {
1313
return func(c *gin.Context) {
1414
apiKey := c.GetHeader("Authorization")
@@ -24,26 +24,26 @@ func APIKeyAuthMiddleware() gin.HandlerFunc {
2424
}
2525
}
2626

27-
// SecurityHeadersMiddleware 设置安全头
27+
// SecurityHeadersMiddleware set security headers
2828
func SecurityHeadersMiddleware() gin.HandlerFunc {
2929
return func(c *gin.Context) {
30-
// 防止 MIME 类型嗅探攻击。
30+
// Prevent MIME type sniffing attacks.
3131
c.Writer.Header().Set("X-Content-Type-Options", "nosniff")
32-
// 防止点击劫持
32+
// Prevent click jacking
3333
c.Writer.Header().Set("X-Frame-Options", "DENY")
34-
// 防止跨站脚本攻击
34+
// Prevent cross-site scripting attacks
3535
c.Writer.Header().Set("X-XSS-Protection", "1; mode=block")
36-
// 实施内容安全策略(CSP),限制资源加载。
36+
// Implement content security policy (CSP), limit resource loading.
3737
c.Writer.Header().Set("Content-Security-Policy", "default-src 'none'")
38-
// 防止浏览器缓存
38+
// Prevent browser caching
3939
c.Writer.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0")
4040
c.Writer.Header().Set("Pragma", "no-cache")
4141
c.Writer.Header().Set("Expires", "0")
4242
c.Next()
4343
}
4444
}
4545

46-
// LimitRequestBody 限制请求体大小
46+
// LimitRequestBody limit request body size
4747
func LimitRequestBody(maxBytes int64) gin.HandlerFunc {
4848
return func(c *gin.Context) {
4949
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
@@ -56,7 +56,7 @@ func LimitRequestBody(maxBytes int64) gin.HandlerFunc {
5656
}
5757
}
5858

59-
// ErrorHandler 统一的错误处理函数
59+
// ErrorHandler unified error handling function
6060
func ErrorHandler(w http.ResponseWriter, errMsg string, statusCode int) {
6161
logger.Logger.Error(errMsg)
6262
w.Header().Set("Content-Type", "application/json")

0 commit comments

Comments
 (0)