Browse Source

可以查询配置文件

qdy 2 months ago
parent
commit
a32962435b

+ 2
- 0
bootstraps/bootstrap.go View File

@@ -185,6 +185,8 @@ func (b *ServiceBootstrapper) runWebService() {
185 185
 	logger.Debug("测试日志是否写入ES.")
186 186
 
187 187
 	log.Printf("服务开始运行...")
188
+	defer b.CleanupDatabase()
189
+
188 190
 	if err := b.WebService.Run(); err != nil {
189 191
 		log.Fatal("服务运行失败:", err)
190 192
 	}

+ 8
- 0
config/config.go View File

@@ -23,6 +23,14 @@ type IConfig interface {
23 23
 	IsRedisConfigured() bool
24 24
 	SetServiceName(name string)
25 25
 	SetServiceVersion(version string)
26
+	SetEnv(name string)
27
+}
28
+
29
+// 根据启动参数设置环境变量
30
+func (c *Config) SetEnv(name string) {
31
+	if c.GetService().Env == "" {
32
+		c.GetService().Env = name
33
+	}
26 34
 }
27 35
 
28 36
 // 设置微服务名称。。如果配置文件设置了,就按配置文件

+ 18
- 21
config/loader.go View File

@@ -10,33 +10,39 @@ import (
10 10
 	"gopkg.in/yaml.v2"
11 11
 )
12 12
 
13
-// LoadConfig 加载配置到注册表
13
+// LoadConfig 从文件加载配置到注册表(保持原有接口不变)
14 14
 func LoadConfig() error {
15
-	// 1. 设置所有注册配置的默认值
16
-	for _, config := range subconfigs.GetAllConfigs() {
17
-		config.SetDefaults()
18
-	}
19
-
20
-	// 2. 查找配置文件
15
+	// 1. 查找配置文件
21 16
 	configFile, err := findConfigFile()
22 17
 	if err != nil {
23 18
 		return err
24 19
 	}
25 20
 
26
-	// 3. 读取文件
21
+	// 2. 读取并解析文件
27 22
 	data, err := os.ReadFile(configFile)
28 23
 	if err != nil {
29 24
 		return fmt.Errorf("read config file error: %v", err)
30 25
 	}
31 26
 
32
-	// 4. 解析为map
33 27
 	var rawConfig map[string]interface{}
34 28
 	err = yaml.Unmarshal(data, &rawConfig)
35 29
 	if err != nil {
36 30
 		return fmt.Errorf("parse yaml error: %v", err)
37 31
 	}
38 32
 
39
-	// 5. 循环注册表,为每个配置加载数据
33
+	// 3. 从map加载配置
34
+	return LoadConfigFromMap(rawConfig)
35
+}
36
+
37
+// LoadConfigFromMap 从map[string]interface{}加载配置到注册表
38
+// 新增方法,供外部调用(比如从数据库加载后使用)
39
+func LoadConfigFromMap(rawConfig map[string]interface{}) error {
40
+	// 1. 设置所有注册配置的默认值
41
+	for _, config := range subconfigs.GetAllConfigs() {
42
+		config.SetDefaults()
43
+	}
44
+
45
+	// 2. 循环注册表,为每个配置加载数据
40 46
 	for name, config := range subconfigs.GetAllConfigs() {
41 47
 		if configData, ok := rawConfig[name].(map[interface{}]interface{}); ok {
42 48
 			// 转换为 map[string]interface{}
@@ -47,17 +53,10 @@ func LoadConfig() error {
47 53
 		}
48 54
 	}
49 55
 
50
-	// // 6. 验证所有配置
51
-	// for name, config := range subconfigs.GetAllConfigs() {
52
-	// 	if err := config.Validate(); err != nil {
53
-	// 		return fmt.Errorf("validate config %s error: %v", name, err)
54
-	// 	}
55
-	// }
56
-
57 56
 	return nil
58 57
 }
59 58
 
60
-// convertMap 转换map类型
59
+// convertMap 转换map类型(内部函数保持不变)
61 60
 func convertMap(input map[interface{}]interface{}) map[string]interface{} {
62 61
 	output := make(map[string]interface{})
63 62
 	for k, v := range input {
@@ -68,7 +67,7 @@ func convertMap(input map[interface{}]interface{}) map[string]interface{} {
68 67
 	return output
69 68
 }
70 69
 
71
-// findConfigFile 查找配置文件
70
+// findConfigFile 查找配置文件(内部函数保持不变)
72 71
 func findConfigFile() (string, error) {
73 72
 	exePath, _ := os.Executable()
74 73
 	exeDir := filepath.Dir(exePath)
@@ -91,8 +90,6 @@ func findConfigFile() (string, error) {
91 90
 		}
92 91
 	}
93 92
 
94
-	//return "", fmt.Errorf("no configuration file found")
95
-
96 93
 	return "", fmt.Errorf(`no configuration file found
97 94
 
98 95
 Searched locations:

+ 1
- 0
config/subconfigs/service_config.go View File

@@ -14,6 +14,7 @@ type ServiceConfig struct {
14 14
 	IdleTimeout    int    `yaml:"idle_timeout"`
15 15
 	TrustedProxies string `yaml:"trusted_proxies"`
16 16
 	InstanceName   string `yaml:"instance-name"`
17
+	Env            string `yaml:"env"`
17 18
 }
18 19
 
19 20
 func NewServiceConfig() *ServiceConfig {

+ 1
- 1
middleware/authMiddleware.go View File

@@ -84,7 +84,7 @@ func sendAuthError(w http.ResponseWriter, message string, format ResponseFormat)
84 84
 		w.Write([]byte("unauthorized," + message + "\n"))
85 85
 	default:
86 86
 		w.Header().Set("Content-Type", "application/json")
87
-		json.NewEncoder(w).Encode(&types.QueryResult{
87
+		json.NewEncoder(w).Encode(&types.QueryResult[map[string]interface{}]{
88 88
 			Success: false,
89 89
 			Error:   message,
90 90
 			Time:    time.Now().Format(time.RFC3339),

+ 9
- 0
myservice/service.go View File

@@ -7,6 +7,7 @@ import (
7 7
 
8 8
 	"git.x2erp.com/qdy/go-base/config"
9 9
 	"github.com/go-micro/plugins/v4/registry/consul"
10
+	"github.com/urfave/cli/v2"
10 11
 	"go-micro.dev/v4/registry"
11 12
 	"go-micro.dev/v4/web"
12 13
 )
@@ -30,6 +31,14 @@ func StartWithRegistry(cfg config.IConfig) web.Service {
30 31
 		web.Registry(consulRegistry),
31 32
 		web.RegisterTTL(30*time.Second),      // Health check interval
32 33
 		web.RegisterInterval(20*time.Second), // Registration interval
34
+		web.Flags(&cli.StringFlag{
35
+			Name:  "env",
36
+			Value: "dev",
37
+			Usage: "环境参数"}),
38
+		web.Action(func(c *cli.Context) {
39
+			cfg.SetEnv(c.String("env"))
40
+			log.Printf("环境参数: %s\n", serviceConfig.Env)
41
+		}),
33 42
 	)
34 43
 
35 44
 	// 3. Initialize service

+ 2
- 10
types/types.go View File

@@ -105,9 +105,9 @@ type QueryRequest struct {
105 105
 }
106 106
 
107 107
 // QueryResult 查询结果
108
-type QueryResult struct {
108
+type QueryResult[T any] struct {
109 109
 	Success    bool                `json:"success"`
110
-	Data       interface{}         `json:"data,omitempty"`
110
+	Data       T                   `json:"data,omitempty"`
111 111
 	Error      string              `json:"error,omitempty"`
112 112
 	Count      int                 `json:"count,omitempty"`
113 113
 	Time       string              `json:"time,omitempty"`
@@ -118,14 +118,6 @@ type QueryResult struct {
118 118
 	Metadata   *ctx.RequestContext `json:"metadata,omitempty"`
119 119
 }
120 120
 
121
-// PageResult 分页结果
122
-type PageResult struct {
123
-	QueryResult
124
-	Page     int `json:"page"`
125
-	PageSize int `json:"pageSize"`
126
-	Total    int `json:"total"`
127
-}
128
-
129 121
 // HealthCheck 健康检查
130 122
 type HealthCheck struct {
131 123
 	Status    string    `json:"status"`

Loading…
Cancel
Save