add Available function for Adapter of package gcfg

This commit is contained in:
John Guo 2021-11-27 01:33:53 +08:00
parent c160500c7d
commit c33378540a
3 changed files with 14 additions and 4 deletions

View File

@ -54,7 +54,10 @@ func NewWithAdapter(adapter Adapter) *Config {
// exists in the configuration directory, it then sets it as the default configuration file. The
// toml file type is the default configuration file type.
func Instance(name ...string) *Config {
key := DefaultName
var (
ctx = context.TODO()
key = DefaultName
)
if len(name) > 0 && name[0] != "" {
key = name[0]
}
@ -67,9 +70,9 @@ func Instance(name ...string) *Config {
// If it's not using default configuration or its configuration file is not available,
// it searches the possible configuration file according to the name and all supported
// file types.
if key != DefaultName || !adapter.Available() {
if key != DefaultName || !adapter.Available(ctx) {
for _, fileType := range supportedFileTypes {
if file := fmt.Sprintf(`%s.%s`, key, fileType); adapter.Available(file) {
if file := fmt.Sprintf(`%s.%s`, key, fileType); adapter.Available(ctx, file) {
adapter.SetFileName(file)
break
}

View File

@ -10,6 +10,13 @@ import "context"
// Adapter is the interface for configuration retrieving.
type Adapter interface {
// Available checks and returns the configuration service is available.
// The optional parameter `pattern` specifies certain configuration resource.
//
// It returns true if configuration file is present in default AdapterFile, or else false.
// Note that this function does not return error as it just does simply check for backend configuration service.
Available(ctx context.Context, pattern ...string) (ok bool)
// Get retrieves and returns value by specified `pattern`.
Get(ctx context.Context, pattern string) (value interface{}, err error)

View File

@ -175,7 +175,7 @@ func (c *AdapterFile) Dump() {
}
// Available checks and returns whether configuration of given `file` is available.
func (c *AdapterFile) Available(fileName ...string) bool {
func (c *AdapterFile) Available(ctx context.Context, fileName ...string) bool {
var (
usedFileName string
)