File: finder_example_test.go

package info (click to toggle)
golang-github-spf13-viper 1.21.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid
  • size: 560 kB
  • sloc: makefile: 64
file content (73 lines) | stat: -rw-r--r-- 1,614 bytes parent folder | download
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
package viper_test

import (
	"fmt"

	"github.com/sagikazarmark/locafero"
	"github.com/spf13/afero"

	"github.com/spf13/viper"
)

func ExampleFinder() {
	fs := afero.NewMemMapFs()

	fs.Mkdir("/home/user", 0o777)

	f, _ := fs.Create("/home/user/myapp.yaml")
	f.WriteString("foo: bar")
	f.Close()

	// HCL will have a "lower" priority in the search order
	fs.Create("/home/user/myapp.hcl")

	finder := locafero.Finder{
		Paths: []string{"/home/user"},
		Names: locafero.NameWithExtensions("myapp", viper.SupportedExts...),
		Type:  locafero.FileTypeFile, // This is important!
	}

	v := viper.NewWithOptions(viper.WithFinder(finder))
	v.SetFs(fs)
	v.ReadInConfig()

	fmt.Println(v.GetString("foo"))

	// Output:
	// bar
}

func ExampleFinders() {
	fs := afero.NewMemMapFs()

	fs.Mkdir("/home/user", 0o777)
	f, _ := fs.Create("/home/user/myapp.yaml")
	f.WriteString("foo: bar")
	f.Close()

	fs.Mkdir("/etc/myapp", 0o777)
	fs.Create("/etc/myapp/config.yaml")

	// Combine multiple finders to search for files in multiple locations with different criteria
	finder := viper.Finders(
		locafero.Finder{
			Paths: []string{"/home/user"},
			Names: locafero.NameWithExtensions("myapp", viper.SupportedExts...),
			Type:  locafero.FileTypeFile, // This is important!
		},
		locafero.Finder{
			Paths: []string{"/etc/myapp"},
			Names: []string{"config.yaml"}, // Only accept YAML files in the system config directory
			Type:  locafero.FileTypeFile,   // This is important!
		},
	)

	v := viper.NewWithOptions(viper.WithFinder(finder))
	v.SetFs(fs)
	v.ReadInConfig()

	fmt.Println(v.GetString("foo"))

	// Output:
	// bar
}