github.heygears.com/openimsdk/tools@v0.0.49/config/config.go (about)

     1  // Copyright © 2024 OpenIM open source community. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package config
    16  
    17  import (
    18  	"os"
    19  	"path/filepath"
    20  
    21  	"github.com/openimsdk/tools/errs"
    22  	"gopkg.in/yaml.v2"
    23  )
    24  
    25  // Loader is responsible for loading configuration files.
    26  type Loader struct {
    27  	PathResolver PathResolver
    28  }
    29  
    30  func NewLoader(pathResolver PathResolver) *Loader {
    31  	return &Loader{PathResolver: pathResolver}
    32  }
    33  
    34  func (c *Loader) InitConfig(config any, configName, configFolderPath string) error {
    35  	configFolderPath, err := c.resolveConfigPath(configName, configFolderPath)
    36  	if err != nil {
    37  		return errs.WrapMsg(err, "resolveConfigPath failed", "configName", configName, "configFolderPath", configFolderPath)
    38  	}
    39  
    40  	data, err := os.ReadFile(configFolderPath)
    41  	if err != nil {
    42  		return errs.WrapMsg(err, "ReadFile failed", "configFolderPath", configFolderPath)
    43  	}
    44  
    45  	if err = yaml.Unmarshal(data, config); err != nil {
    46  		return errs.WrapMsg(err, "failed to unmarshal config data", "configName", configName)
    47  	}
    48  
    49  	return nil
    50  }
    51  
    52  func (c *Loader) resolveConfigPath(configName, configFolderPath string) (string, error) {
    53  	if configFolderPath == "" {
    54  		var err error
    55  		configFolderPath, err = c.PathResolver.GetDefaultConfigPath()
    56  		if err != nil {
    57  			return "", errs.WrapMsg(err, "GetDefaultConfigPath failed", "configName", configName)
    58  		}
    59  	}
    60  
    61  	configFilePath := filepath.Join(configFolderPath, configName)
    62  	if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
    63  		// Attempt to load from project root if not found in specified path
    64  		projectRoot, err := c.PathResolver.GetProjectRoot()
    65  		if err != nil {
    66  			return "", err
    67  		}
    68  		configFilePath = filepath.Join(projectRoot, "config", configName)
    69  	}
    70  	return configFilePath, nil
    71  }