Repository navigation
Expand file tree
/
Copy pathexample_collectors_test.go
More file actions
340 lines (257 loc) · 7.88 KB
/
Copy pathexample_collectors_test.go
File metadata and controls
340 lines (257 loc) · 7.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package config_test
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/tarantool/go-config/v2"
"github.com/tarantool/go-config/v2/collectors"
)
// Example_envCollector demonstrates the Env collector which reads
// configuration from environment variables. It supports prefix filtering,
// custom delimiters, and custom key transformation functions.
func Example_envCollector() {
// Set environment variables with a unique prefix.
_ = os.Setenv("EXAMPLEAPP_DB_HOST", "localhost")
_ = os.Setenv("EXAMPLEAPP_DB_PORT", "5432")
defer func() { _ = os.Unsetenv("EXAMPLEAPP_DB_HOST") }()
defer func() { _ = os.Unsetenv("EXAMPLEAPP_DB_PORT") }()
// Basic usage: prefix strips "EXAMPLEAPP_", underscore splits into hierarchy.
envCollector := collectors.NewEnv().
WithPrefix("EXAMPLEAPP_").
WithDelimiter("_").
WithName("env")
builder := config.NewBuilder()
builder = builder.AddCollector(envCollector)
cfg, errs := builder.Build(context.Background())
if len(errs) > 0 {
fmt.Printf("Build errors: %v\n", errs)
return
}
var host string
_, err := cfg.Get(config.NewKeyPath("db/host"), &host)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("DB host: %s\n", host)
var port string
_, err = cfg.Get(config.NewKeyPath("db/port"), &port)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("DB port: %s\n", port)
// Custom transform: convert env var names to a custom key path.
_ = os.Setenv("EXAMPLEAPP_SERVER__HOST", "0.0.0.0")
defer func() { _ = os.Unsetenv("EXAMPLEAPP_SERVER__HOST") }()
transformCollector := collectors.NewEnv().
WithPrefix("EXAMPLEAPP_SERVER__").
WithTransform(func(key string) config.KeyPath {
// Use double underscore as separator, preserve case.
parts := strings.Split(strings.ToLower(key), "__")
return config.NewKeyPathFromSegments(parts)
}).
WithName("env-transform")
builder = config.NewBuilder()
builder = builder.AddCollector(transformCollector)
cfg, errs = builder.Build(context.Background())
if len(errs) > 0 {
fmt.Printf("Build errors: %v\n", errs)
return
}
var serverHost string
_, err = cfg.Get(config.NewKeyPath("host"), &serverHost)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("Server host: %s\n", serverHost)
// Output:
// DB host: localhost
// DB port: 5432
// Server host: 0.0.0.0
}
// Example_directoryCollector demonstrates the Directory collector which reads
// all configuration files with a given extension from a directory and merges
// them into a unified configuration tree.
func Example_directoryCollector() {
// Create a temporary directory with configuration files.
dir, err := os.MkdirTemp("", "go-config-example-*")
if err != nil {
fmt.Printf("MkdirTemp error: %v\n", err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
// Write YAML configuration files.
err = os.WriteFile(filepath.Join(dir, "app.yaml"),
[]byte("app:\n name: myservice\n port: 8080\n"), 0o600)
if err != nil {
fmt.Printf("WriteFile error: %v\n", err)
return
}
err = os.WriteFile(filepath.Join(dir, "db.yaml"),
[]byte("database:\n host: postgres\n port: 5432\n"), 0o600)
if err != nil {
fmt.Printf("WriteFile error: %v\n", err)
return
}
// Create a subdirectory with another config file.
subdir := filepath.Join(dir, "extra")
err = os.MkdirAll(subdir, 0o750)
if err != nil {
fmt.Printf("MkdirAll error: %v\n", err)
return
}
err = os.WriteFile(filepath.Join(subdir, "cache.yaml"),
[]byte("cache:\n ttl: 300\n"), 0o600)
if err != nil {
fmt.Printf("WriteFile error: %v\n", err)
return
}
// Read only top-level files (non-recursive).
collector := collectors.NewDirectory(dir, ".yaml", collectors.NewYamlFormat()).
WithName("config")
builder := config.NewBuilder()
builder = builder.AddCollector(collector)
cfg, errs := builder.Build(context.Background())
if len(errs) > 0 {
fmt.Printf("Build errors: %v\n", errs)
return
}
var appName string
_, err = cfg.Get(config.NewKeyPath("app/name"), &appName)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("App: %s\n", appName)
var dbHost string
_, err = cfg.Get(config.NewKeyPath("database/host"), &dbHost)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("DB host: %s\n", dbHost)
// Subdirectory files are not read without recursive mode.
_, ok := cfg.Lookup(config.NewKeyPath("cache/ttl"))
fmt.Printf("Cache TTL found (non-recursive): %v\n", ok)
// Enable recursive scanning to include subdirectories.
recursiveCollector := collectors.NewDirectory(dir, ".yaml", collectors.NewYamlFormat()).
WithRecursive(true)
builder = config.NewBuilder()
builder = builder.AddCollector(recursiveCollector)
cfg, errs = builder.Build(context.Background())
if len(errs) > 0 {
fmt.Printf("Build errors: %v\n", errs)
return
}
var ttl int
_, err = cfg.Get(config.NewKeyPath("cache/ttl"), &ttl)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("Cache TTL (recursive): %d\n", ttl)
// Output:
// App: myservice
// DB host: postgres
// Cache TTL found (non-recursive): false
// Cache TTL (recursive): 300
}
// Example_fileSource demonstrates reading configuration from a single YAML
// file using collectors.NewFile() as a DataSource with collectors.NewSource().
func Example_fileSource() {
// Create a temporary YAML file.
dir, err := os.MkdirTemp("", "go-config-file-example-*")
if err != nil {
fmt.Printf("MkdirTemp error: %v\n", err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
filePath := filepath.Join(dir, "config.yaml")
err = os.WriteFile(filePath,
[]byte("server:\n host: localhost\n port: 8080\nlog_level: info\n"), 0o600)
if err != nil {
fmt.Printf("WriteFile error: %v\n", err)
return
}
// Create a File data source and wrap it with a YAML format.
file := collectors.NewFile(filePath)
collector, err := collectors.NewSource(context.Background(), file, collectors.NewYamlFormat())
if err != nil {
fmt.Printf("NewSource error: %v\n", err)
return
}
builder := config.NewBuilder()
builder = builder.AddCollector(collector)
cfg, errs := builder.Build(context.Background())
if len(errs) > 0 {
fmt.Printf("Build errors: %v\n", errs)
return
}
var host string
_, err = cfg.Get(config.NewKeyPath("server/host"), &host)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("Host: %s\n", host)
var port int
_, err = cfg.Get(config.NewKeyPath("server/port"), &port)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("Port: %d\n", port)
var logLevel string
_, err = cfg.Get(config.NewKeyPath("log_level"), &logLevel)
if err != nil {
fmt.Printf("Get error: %v\n", err)
return
}
fmt.Printf("Log level: %s\n", logLevel)
// Output:
// Host: localhost
// Port: 8080
// Log level: info
}
// Example_structCollector demonstrates the Struct collector which reads
// configuration directly from a Go struct, using `config` (or `yaml`) tags
// for key names.
func Example_structCollector() {
type DB struct {
Host string `config:"host"`
Port int `config:"port"`
}
type AppConfig struct {
Name string `config:"name"`
DB DB `config:"db"`
Debug bool `config:"debug,omitempty"`
}
collector := collectors.NewStruct(AppConfig{
Name: "myapp",
DB: DB{Host: "localhost", Port: 5432},
}).WithName("defaults")
builder := config.NewBuilder()
builder = builder.AddCollector(collector)
cfg, errs := builder.Build(context.Background())
if len(errs) > 0 {
fmt.Printf("Build errors: %v\n", errs)
return
}
var name string
_, _ = cfg.Get(config.NewKeyPath("name"), &name)
var host string
_, _ = cfg.Get(config.NewKeyPath("db/host"), &host)
var port int
_, _ = cfg.Get(config.NewKeyPath("db/port"), &port)
fmt.Printf("name: %s\n", name)
fmt.Printf("db.host: %s\n", host)
fmt.Printf("db.port: %d\n", port)
// Output:
// name: myapp
// db.host: localhost
// db.port: 5432
}