浏览代码

踢出gin

qdy 3 个月前
父节点
当前提交
3e0d20e16a
共有 6 个文件被更改,包括 86 次插入228 次删除
  1. 0
    41
      functions/heath.go
  2. 0
    32
      functions/info.go
  3. 20
    41
      functions/query_csv.go
  4. 7
    17
      functions/query_json.go
  5. 0
    3
      go.mod
  6. 59
    94
      main.go

+ 0
- 41
functions/heath.go 查看文件

@@ -1,41 +0,0 @@
1
-package functions
2
-
3
-import (
4
-	"time"
5
-
6
-	"github.com/gin-gonic/gin"
7
-
8
-	"git.x2erp.com/qdy/go-base/types"
9
-	"git.x2erp.com/qdy/go-db/factory/database"
10
-)
11
-
12
-// HealthHandler 返回一个处理函数
13
-func HealthHandler(dbFactory *database.DBFactory, dbType string) gin.HandlerFunc {
14
-	return func(c *gin.Context) {
15
-
16
-		dbFactory.TestConnection(dbType)
17
-		err := dbFactory.TestConnection(dbType)
18
-		success := err == nil
19
-
20
-		status := "DOWN"
21
-		if success {
22
-			status = "UP"
23
-		}
24
-
25
-		c.JSON(200, &types.QueryResult{
26
-			Success: success,
27
-			Data: map[string]interface{}{
28
-				"status":         status,
29
-				"time":           time.Now().Format(time.RFC3339),
30
-				"database":       dbType,
31
-				"databaseStatus": status,
32
-			},
33
-			Error: func() string {
34
-				if err != nil {
35
-					return err.Error()
36
-				}
37
-				return ""
38
-			}(),
39
-		})
40
-	}
41
-}

+ 0
- 32
functions/info.go 查看文件

@@ -1,32 +0,0 @@
1
-package functions
2
-
3
-import (
4
-	"time"
5
-
6
-	"github.com/gin-gonic/gin"
7
-
8
-	"git.x2erp.com/qdy/go-base/config"
9
-	"git.x2erp.com/qdy/go-base/types"
10
-	"git.x2erp.com/qdy/go-db/factory/database"
11
-)
12
-
13
-// InfoHandler 数据库信息
14
-func InfoHandler(dbFactory *database.DBFactory) gin.HandlerFunc {
15
-	return func(c *gin.Context) {
16
-		dbConfig := config.GetConfig()
17
-		drivers := dbFactory.GetAvailableDrivers()
18
-
19
-		c.JSON(200, &types.QueryResult{
20
-			Success: true,
21
-			Data: map[string]interface{}{
22
-				"database_type":     dbConfig.GetDatabase().Type,
23
-				"database_host":     dbConfig.GetDatabase().Host,
24
-				"database_port":     dbConfig.GetDatabase().Port,
25
-				"database_name":     dbConfig.GetDatabase().Database,
26
-				"available_drivers": drivers,
27
-				"service_time":      time.Now().Format(time.RFC3339),
28
-			},
29
-			Error: "",
30
-		})
31
-	}
32
-}

+ 20
- 41
functions/query_csv.go 查看文件

@@ -1,60 +1,39 @@
1 1
 package functions
2 2
 
3 3
 import (
4
-	"github.com/gin-gonic/gin"
4
+	"log"
5 5
 
6
-	"git.x2erp.com/qdy/go-base/mycsv"
7 6
 	"git.x2erp.com/qdy/go-base/types"
8 7
 	"git.x2erp.com/qdy/go-db/factory/database"
9 8
 )
10 9
 
11
-// 统一的错误响应处理
12
-func handleErrorResponseCSV(c *gin.Context, err error) {
13
-	errorCSV := mycsv.CreateStringToCSV(err.Error())
14
-	c.Header("Content-Type", "text/csv; charset=utf-8")
15
-	c.Header("X-Error", "true")
16
-	c.Data(400, "text/csv; charset=utf-8", errorCSV)
17
-}
18
-
19
-// 统一的成功响应处理
20
-func handleSuccessResponseCSV(c *gin.Context, csvData []byte) {
21
-	c.Header("Content-Type", "text/csv; charset=utf-8")
22
-	c.Data(200, "text/csv; charset=utf-8", csvData)
23
-}
24
-
25 10
 // 执行查询,返回CSV数据格式。无参数查询
26
-func QueryToCSV(dbFactory *database.DBFactory) func(c *gin.Context, req types.QueryRequest) {
27
-	return func(c *gin.Context, req types.QueryRequest) {
28
-		csvData, err := dbFactory.QueryToCSV(req.SQL, req.WriterHeader)
29
-		if err != nil {
30
-			handleErrorResponseCSV(c, err)
31
-			return
32
-		}
33
-		handleSuccessResponseCSV(c, csvData)
11
+func QueryToCSV(dbFactory *database.DBFactory, req types.QueryRequest) []byte {
12
+	csvData, err := dbFactory.QueryToCSV(req.SQL, req.WriterHeader)
13
+	if err != nil {
14
+		log.Fatalf("QueryToCSV error: %v", err)
15
+
34 16
 	}
17
+	return csvData
35 18
 }
36 19
 
37 20
 // 执行查询,返回CSV数据格式。带参数名称进行查询
38
-func QueryParamNameToCSV(dbFactory *database.DBFactory) func(c *gin.Context, req types.QueryRequest) {
39
-	return func(c *gin.Context, req types.QueryRequest) {
40
-
41
-		csvData, err := dbFactory.QueryParamsNameToCSV(req.SQL, req.WriterHeader, req.Params)
42
-		if err != nil {
43
-			handleErrorResponseCSV(c, err)
44
-			return
45
-		}
46
-		handleSuccessResponseCSV(c, csvData)
21
+func QueryParamNameToCSV(dbFactory *database.DBFactory, req types.QueryRequest) []byte {
22
+
23
+	csvData, err := dbFactory.QueryParamsNameToCSV(req.SQL, req.WriterHeader, req.Params)
24
+	if err != nil {
25
+		log.Fatalf("QueryParamNameToCSV Error: %v", err)
26
+
47 27
 	}
28
+	return csvData
48 29
 }
49 30
 
50 31
 // 执行查询,返回CSV数据格式。带占位参数进行查询
51
-func QueryPositionalToCSV(dbFactory *database.DBFactory) func(c *gin.Context, req types.QueryRequest) {
52
-	return func(c *gin.Context, req types.QueryRequest) {
53
-		csvData, err := dbFactory.QueryPositionalToCSV(req.SQL, req.WriterHeader, req.PositionalParams)
54
-		if err != nil {
55
-			handleErrorResponseCSV(c, err)
56
-			return
57
-		}
58
-		handleSuccessResponseCSV(c, csvData)
32
+func QueryPositionalToCSV(dbFactory *database.DBFactory, req types.QueryRequest) []byte {
33
+	csvData, err := dbFactory.QueryPositionalToCSV(req.SQL, req.WriterHeader, req.PositionalParams)
34
+	if err != nil {
35
+		log.Fatalf("QueryParamNameToCSV Error: %v", err)
36
+
59 37
 	}
38
+	return csvData
60 39
 }

+ 7
- 17
functions/query_json.go 查看文件

@@ -1,33 +1,23 @@
1 1
 package functions
2 2
 
3 3
 import (
4
-	"github.com/gin-gonic/gin"
5
-
6 4
 	"git.x2erp.com/qdy/go-base/types"
7 5
 	"git.x2erp.com/qdy/go-db/factory/database"
8 6
 )
9 7
 
10 8
 // 执行查询,返回CSV数据格式。无参数查询
11
-func QueryToJSON(dbFactory *database.DBFactory) func(c *gin.Context, req types.QueryRequest) {
12
-	return func(c *gin.Context, req types.QueryRequest) {
13
-		result := dbFactory.QueryToJSON(req.SQL)
14
-		c.JSON(200, result)
15
-	}
9
+func QueryToJSON(dbFactory *database.DBFactory, req types.QueryRequest) *types.QueryResult {
10
+	return dbFactory.QueryToJSON(req.SQL)
11
+
16 12
 }
17 13
 
18 14
 // 执行查询,返回CSV数据格式。带参数名称进行查询
19
-func QueryParamNameToJSON(dbFactory *database.DBFactory) func(c *gin.Context, req types.QueryRequest) {
20
-	return func(c *gin.Context, req types.QueryRequest) {
21
-		result := dbFactory.QueryParamsNameToJSON(req.SQL, req.Params)
22
-		c.JSON(200, result)
23
-	}
15
+func QueryParamNameToJSON(dbFactory *database.DBFactory, req types.QueryRequest) *types.QueryResult {
16
+	return dbFactory.QueryParamsNameToJSON(req.SQL, req.Params)
24 17
 }
25 18
 
26 19
 // 执行查询,返回JSON数据格式。带占位参数进行查询
27
-func QueryPositionalToJSON(dbFactory *database.DBFactory) func(c *gin.Context, req types.QueryRequest) {
28
-	return func(c *gin.Context, req types.QueryRequest) {
29
-		result := dbFactory.QueryPositionalToJSON(req.SQL, req.PositionalParams)
20
+func QueryPositionalToJSON(dbFactory *database.DBFactory, req types.QueryRequest) *types.QueryResult {
21
+	return dbFactory.QueryPositionalToJSON(req.SQL, req.PositionalParams)
30 22
 
31
-		c.JSON(200, result)
32
-	}
33 23
 }

+ 0
- 3
go.mod 查看文件

@@ -5,8 +5,6 @@ go 1.25.4
5 5
 require (
6 6
 	git.x2erp.com/qdy/go-base v0.1.44
7 7
 	git.x2erp.com/qdy/go-db v0.1.42
8
-	github.com/gin-gonic/gin v1.11.0
9
-	github.com/go-sql-driver/mysql v1.9.3
10 8
 )
11 9
 
12 10
 require (
@@ -52,6 +50,5 @@ require (
52 50
 	golang.org/x/sys v0.38.0 // indirect
53 51
 	golang.org/x/text v0.31.0 // indirect
54 52
 	golang.org/x/tools v0.38.0 // indirect
55
-	google.golang.org/protobuf v1.36.9 // indirect
56 53
 	gopkg.in/yaml.v2 v2.4.0 // indirect
57 54
 )

+ 59
- 94
main.go 查看文件

@@ -1,146 +1,109 @@
1 1
 package main
2 2
 
3 3
 import (
4
-	"fmt"
5 4
 	"log"
6 5
 	"net/http"
7 6
 	"os"
8 7
 	"os/signal"
9
-	"strings"
10 8
 	"syscall"
11
-	"time"
12 9
 
13 10
 	"git.x2erp.com/qdy/go-base/config"
14
-	"git.x2erp.com/qdy/go-base/types"
11
+	"git.x2erp.com/qdy/go-base/micro"
12
+	mymiddleware "git.x2erp.com/qdy/go-base/myMiddleware"
15 13
 	"git.x2erp.com/qdy/go-db/factory/database"
16
-	"git.x2erp.com/qdy/go-service-agent/auth"
14
+	"git.x2erp.com/qdy/go-db/myhandle"
17 15
 	"git.x2erp.com/qdy/go-service-agent/functions"
18
-	"github.com/gin-gonic/gin"
16
+	"go-micro.dev/v4/web"
19 17
 )
20 18
 
21 19
 func main() {
22
-
23 20
 	cfg := config.GetConfig()
21
+	serviceConfig := cfg.GetService()
24 22
 
25
-	log.Printf("Service Port: %d", cfg.GetService().Port)
26
-	log.Printf("Service IdleTimeout: %d", cfg.GetService().IdleTimeout)
27
-	log.Printf("Service ReadTimeout: %d", cfg.GetService().ReadTimeout)
28
-	log.Printf("Service WriteTimeout: %d", cfg.GetService().WriteTimeout)
29
-	log.Printf("Service TrustedProxies: %s", cfg.GetService().TrustedProxies)
23
+	log.Printf("Service Port: %d", serviceConfig.Port)
24
+	log.Printf("Service IdleTimeout: %d", serviceConfig.IdleTimeout)
25
+	log.Printf("Service ReadTimeout: %d", serviceConfig.ReadTimeout)
26
+	log.Printf("Service WriteTimeout: %d", serviceConfig.WriteTimeout)
27
+	log.Printf("Service TrustedProxies: %s", serviceConfig.TrustedProxies)
30 28
 
31 29
 	log.Printf("Using database type: %s", cfg.GetDatabase().Type)
32 30
 	log.Printf("Database host: %s:%d", cfg.GetDatabase().Host, cfg.GetDatabase().Port)
33 31
 	log.Printf("Database name: %s", cfg.GetDatabase().Database)
34 32
 	log.Println("Database connection test passed!")
35 33
 
36
-	// 3. 启动Gin HTTP服务
37
-	startHTTPServer()
34
+	// 启动微服务
35
+	startMicroService()
38 36
 }
39 37
 
40
-// 启动HTTP服务器
41
-func startHTTPServer() {
42
-	//建立路由
43
-	router := gin.Default()
38
+// 启动微服务
39
+func startMicroService() {
44 40
 	cfg := config.GetConfig()
45 41
 	serviceConfig := cfg.GetService()
46 42
 
43
+	// 初始化数据库
47 44
 	dbFactory, err := database.GetDBFactory()
48 45
 	if err != nil {
49 46
 		log.Fatalf("Failed to create DB factory: %v", err)
50 47
 	}
51
-	// 设置优雅关闭
52
-	setupGracefulShutdown(dbFactory)
53 48
 	defer func() {
54
-		dbFactory.Close()
55
-		log.Println("Database connection closed")
49
+		if err := dbFactory.Close(); err != nil {
50
+			log.Printf("Database close error: %v", err)
51
+		}
56 52
 	}()
57 53
 
58
-	// 核心路由
59
-	router.GET("/api/health", functions.HealthHandler(dbFactory, cfg.GetDatabase().Type))
60
-	router.POST("/api/query", auth.AuthMiddleware(), withQueryRequest(functions.QueryToJSON(dbFactory)))
61
-	router.POST("/api/query/csv", auth.AuthMiddleware(), withQueryRequest(functions.QueryToCSV(dbFactory)))
62
-	router.POST("/api/query/csv/param", auth.AuthMiddleware(), withQueryRequest(functions.QueryPositionalToCSV(dbFactory)))
63
-	router.GET("/api/info", functions.InfoHandler(dbFactory))
64
-
65
-	// 日志输出配置信息
66
-	log.Printf("Service Port: %d", serviceConfig.Port)
67
-	log.Printf("Service IdleTimeout: %d", serviceConfig.IdleTimeout)
68
-	log.Printf("Service ReadTimeout: %d", serviceConfig.ReadTimeout)
69
-	log.Printf("Service WriteTimeout: %d", serviceConfig.WriteTimeout)
70
-	log.Printf("Service TrustedProxies: %s", serviceConfig.TrustedProxies)
54
+	// 设置优雅关闭
55
+	setupGracefulShutdown(dbFactory)
71 56
 
72
-	// 设置可信代理
73
-	setupTrustedProxies(router, serviceConfig.TrustedProxies)
57
+	webService := micro.StartStandalone(cfg)
74 58
 
75
-	// 创建HTTP服务器配置
76
-	server := &http.Server{
77
-		Addr:         fmt.Sprintf(":%d", serviceConfig.Port),
78
-		Handler:      router,
79
-		IdleTimeout:  time.Duration(serviceConfig.IdleTimeout) * time.Second,
80
-		ReadTimeout:  time.Duration(serviceConfig.ReadTimeout) * time.Second,
81
-		WriteTimeout: time.Duration(serviceConfig.WriteTimeout) * time.Second,
82
-	}
59
+	// 注册HTTP路由到webService
60
+	registerRoutes(webService, dbFactory, cfg)
83 61
 
84
-	log.Printf("Starting HTTP server on port %d", serviceConfig.Port)
85
-	if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
86
-		log.Fatalf("Failed to start server: %v", err)
87
-	}
62
+	// 等待服务运行
63
+	log.Printf("Service started successfully")
64
+	log.Printf("   • Service: %s", serviceConfig.ServiceName)
65
+	log.Printf("   • Port: %d", serviceConfig.Port)
66
+	log.Printf("   • Mode: %s", getServiceMode(cfg))
88 67
 
68
+	// 保持主程序运行
69
+	select {}
89 70
 }
90 71
 
91
-// 参数绑定包装器
92
-func withQueryRequest(handler func(c *gin.Context, req types.QueryRequest)) gin.HandlerFunc {
93
-	return func(c *gin.Context) {
94
-		var req types.QueryRequest
95
-		if err := c.ShouldBindJSON(&req); err != nil {
96
-			c.JSON(400, &types.QueryResult{
97
-				Success: false,
98
-				Error:   "Invalid request: " + err.Error(),
99
-				Data:    nil,
100
-			})
101
-			return
102
-		}
103
-
104
-		handler(c, req)
105
-	}
72
+// 判断是否使用注册中心
73
+func shouldUseRegistry(cfg config.IConfig) bool {
74
+	microConfig := cfg.GetMicro()
75
+	// 如果有配置注册中心地址且不为空,则使用注册中心
76
+	return microConfig.RegistryAddress != ""
106 77
 }
107 78
 
108
-// 设置可信代理
109
-func setupTrustedProxies(router *gin.Engine, trustedProxiesStr string) {
110
-	if trustedProxiesStr == "" {
111
-		setupTrustedProxiesRouter(router, nil)
112
-		return
113
-	}
114
-
115
-	// 按逗号分割字符串,并去除空格
116
-	proxies := strings.Split(trustedProxiesStr, ",")
117
-	trimmedProxies := make([]string, 0, len(proxies))
118
-
119
-	for _, proxy := range proxies {
120
-		trimmed := strings.TrimSpace(proxy)
121
-		if trimmed != "" {
122
-			trimmedProxies = append(trimmedProxies, trimmed)
123
-		}
124
-	}
125
-
126
-	if len(trimmedProxies) > 0 {
127
-		setupTrustedProxiesRouter(router, trimmedProxies)
128
-	} else {
129
-		setupTrustedProxiesRouter(router, nil)
79
+// 获取服务模式描述
80
+func getServiceMode(cfg config.IConfig) string {
81
+	if shouldUseRegistry(cfg) {
82
+		return "With Service Discovery"
130 83
 	}
84
+	return "Standalone"
131 85
 }
132 86
 
133
-func setupTrustedProxiesRouter(router *gin.Engine, trimmedProxies []string) {
87
+// 注册所有路由
88
+func registerRoutes(webService web.Service, dbFactory *database.DBFactory, cfg config.IConfig) {
134 89
 
135
-	err := router.SetTrustedProxies(trimmedProxies)
136
-	if err != nil {
137
-		log.Printf("Warning: Failed to set trusted proxies: %v", err)
138
-	} else {
139
-		log.Printf("Trusted proxies set: %v", trimmedProxies)
140
-	}
90
+	// 查询接口 - JSON
91
+	webService.Handle("/api/query/json", mymiddleware.JWTAuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
92
+		myhandle.QueryHandlerJson(w, r, dbFactory, functions.QueryToJSON)
93
+	})))
141 94
 
95
+	// 查询接口 - CSV
96
+	webService.Handle("/api/query/csv", mymiddleware.JWTAuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
97
+		myhandle.QueryHandlerBytes(w, r, dbFactory, functions.QueryToCSV)
98
+	})))
99
+
100
+	// 查询接口 - CSV with positional params
101
+	webService.Handle("/api/query/csv/param", mymiddleware.JWTAuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
102
+		myhandle.QueryHandlerBytes(w, r, dbFactory, functions.QueryPositionalToCSV)
103
+	})))
142 104
 }
143 105
 
106
+// 设置优雅关闭
144 107
 func setupGracefulShutdown(dbFactory *database.DBFactory) {
145 108
 	signalCh := make(chan os.Signal, 1)
146 109
 	signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)
@@ -148,7 +111,9 @@ func setupGracefulShutdown(dbFactory *database.DBFactory) {
148 111
 	go func() {
149 112
 		<-signalCh
150 113
 		log.Println("\nReceived shutdown signal, closing database connection...")
151
-		dbFactory.Close()
114
+		if err := dbFactory.Close(); err != nil {
115
+			log.Printf("Error closing database: %v", err)
116
+		}
152 117
 		log.Println("Database connection closed gracefully")
153 118
 		os.Exit(0)
154 119
 	}()

正在加载...
取消
保存