Explorar el Código

可以查询配置文件

qdy hace 2 meses
padre
commit
a32962435b

+ 2
- 0
bootstraps/bootstrap.go Ver fichero

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

+ 8
- 0
config/config.go Ver fichero

23
 	IsRedisConfigured() bool
23
 	IsRedisConfigured() bool
24
 	SetServiceName(name string)
24
 	SetServiceName(name string)
25
 	SetServiceVersion(version string)
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 Ver fichero

10
 	"gopkg.in/yaml.v2"
10
 	"gopkg.in/yaml.v2"
11
 )
11
 )
12
 
12
 
13
-// LoadConfig 加载配置到注册表
13
+// LoadConfig 从文件加载配置到注册表(保持原有接口不变)
14
 func LoadConfig() error {
14
 func LoadConfig() error {
15
-	// 1. 设置所有注册配置的默认值
16
-	for _, config := range subconfigs.GetAllConfigs() {
17
-		config.SetDefaults()
18
-	}
19
-
20
-	// 2. 查找配置文件
15
+	// 1. 查找配置文件
21
 	configFile, err := findConfigFile()
16
 	configFile, err := findConfigFile()
22
 	if err != nil {
17
 	if err != nil {
23
 		return err
18
 		return err
24
 	}
19
 	}
25
 
20
 
26
-	// 3. 读取文件
21
+	// 2. 读取并解析文件
27
 	data, err := os.ReadFile(configFile)
22
 	data, err := os.ReadFile(configFile)
28
 	if err != nil {
23
 	if err != nil {
29
 		return fmt.Errorf("read config file error: %v", err)
24
 		return fmt.Errorf("read config file error: %v", err)
30
 	}
25
 	}
31
 
26
 
32
-	// 4. 解析为map
33
 	var rawConfig map[string]interface{}
27
 	var rawConfig map[string]interface{}
34
 	err = yaml.Unmarshal(data, &rawConfig)
28
 	err = yaml.Unmarshal(data, &rawConfig)
35
 	if err != nil {
29
 	if err != nil {
36
 		return fmt.Errorf("parse yaml error: %v", err)
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
 	for name, config := range subconfigs.GetAllConfigs() {
46
 	for name, config := range subconfigs.GetAllConfigs() {
41
 		if configData, ok := rawConfig[name].(map[interface{}]interface{}); ok {
47
 		if configData, ok := rawConfig[name].(map[interface{}]interface{}); ok {
42
 			// 转换为 map[string]interface{}
48
 			// 转换为 map[string]interface{}
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
 	return nil
56
 	return nil
58
 }
57
 }
59
 
58
 
60
-// convertMap 转换map类型
59
+// convertMap 转换map类型(内部函数保持不变)
61
 func convertMap(input map[interface{}]interface{}) map[string]interface{} {
60
 func convertMap(input map[interface{}]interface{}) map[string]interface{} {
62
 	output := make(map[string]interface{})
61
 	output := make(map[string]interface{})
63
 	for k, v := range input {
62
 	for k, v := range input {
68
 	return output
67
 	return output
69
 }
68
 }
70
 
69
 
71
-// findConfigFile 查找配置文件
70
+// findConfigFile 查找配置文件(内部函数保持不变)
72
 func findConfigFile() (string, error) {
71
 func findConfigFile() (string, error) {
73
 	exePath, _ := os.Executable()
72
 	exePath, _ := os.Executable()
74
 	exeDir := filepath.Dir(exePath)
73
 	exeDir := filepath.Dir(exePath)
91
 		}
90
 		}
92
 	}
91
 	}
93
 
92
 
94
-	//return "", fmt.Errorf("no configuration file found")
95
-
96
 	return "", fmt.Errorf(`no configuration file found
93
 	return "", fmt.Errorf(`no configuration file found
97
 
94
 
98
 Searched locations:
95
 Searched locations:

+ 1
- 0
config/subconfigs/service_config.go Ver fichero

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

+ 1
- 1
middleware/authMiddleware.go Ver fichero

84
 		w.Write([]byte("unauthorized," + message + "\n"))
84
 		w.Write([]byte("unauthorized," + message + "\n"))
85
 	default:
85
 	default:
86
 		w.Header().Set("Content-Type", "application/json")
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
 			Success: false,
88
 			Success: false,
89
 			Error:   message,
89
 			Error:   message,
90
 			Time:    time.Now().Format(time.RFC3339),
90
 			Time:    time.Now().Format(time.RFC3339),

+ 9
- 0
myservice/service.go Ver fichero

7
 
7
 
8
 	"git.x2erp.com/qdy/go-base/config"
8
 	"git.x2erp.com/qdy/go-base/config"
9
 	"github.com/go-micro/plugins/v4/registry/consul"
9
 	"github.com/go-micro/plugins/v4/registry/consul"
10
+	"github.com/urfave/cli/v2"
10
 	"go-micro.dev/v4/registry"
11
 	"go-micro.dev/v4/registry"
11
 	"go-micro.dev/v4/web"
12
 	"go-micro.dev/v4/web"
12
 )
13
 )
30
 		web.Registry(consulRegistry),
31
 		web.Registry(consulRegistry),
31
 		web.RegisterTTL(30*time.Second),      // Health check interval
32
 		web.RegisterTTL(30*time.Second),      // Health check interval
32
 		web.RegisterInterval(20*time.Second), // Registration interval
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
 	// 3. Initialize service
44
 	// 3. Initialize service

+ 2
- 10
types/types.go Ver fichero

105
 }
105
 }
106
 
106
 
107
 // QueryResult 查询结果
107
 // QueryResult 查询结果
108
-type QueryResult struct {
108
+type QueryResult[T any] struct {
109
 	Success    bool                `json:"success"`
109
 	Success    bool                `json:"success"`
110
-	Data       interface{}         `json:"data,omitempty"`
110
+	Data       T                   `json:"data,omitempty"`
111
 	Error      string              `json:"error,omitempty"`
111
 	Error      string              `json:"error,omitempty"`
112
 	Count      int                 `json:"count,omitempty"`
112
 	Count      int                 `json:"count,omitempty"`
113
 	Time       string              `json:"time,omitempty"`
113
 	Time       string              `json:"time,omitempty"`
118
 	Metadata   *ctx.RequestContext `json:"metadata,omitempty"`
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
 // HealthCheck 健康检查
121
 // HealthCheck 健康检查
130
 type HealthCheck struct {
122
 type HealthCheck struct {
131
 	Status    string    `json:"status"`
123
 	Status    string    `json:"status"`

Loading…
Cancelar
Guardar