github.com/lingyao2333/mo-zero@v1.4.1/core/conf/config.go (about)

     1  package conf
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"os"
     7  	"path"
     8  	"strings"
     9  
    10  	"github.com/lingyao2333/mo-zero/core/mapping"
    11  )
    12  
    13  var loaders = map[string]func([]byte, interface{}) error{
    14  	".json": LoadFromJsonBytes,
    15  	".toml": LoadFromTomlBytes,
    16  	".yaml": LoadFromYamlBytes,
    17  	".yml":  LoadFromYamlBytes,
    18  }
    19  
    20  // Load loads config into v from file, .json, .yaml and .yml are acceptable.
    21  func Load(file string, v interface{}, opts ...Option) error {
    22  	content, err := os.ReadFile(file)
    23  	if err != nil {
    24  		return err
    25  	}
    26  
    27  	loader, ok := loaders[strings.ToLower(path.Ext(file))]
    28  	if !ok {
    29  		return fmt.Errorf("unrecognized file type: %s", file)
    30  	}
    31  
    32  	var opt options
    33  	for _, o := range opts {
    34  		o(&opt)
    35  	}
    36  
    37  	if opt.env {
    38  		return loader([]byte(os.ExpandEnv(string(content))), v)
    39  	}
    40  
    41  	return loader(content, v)
    42  }
    43  
    44  // LoadConfig loads config into v from file, .json, .yaml and .yml are acceptable.
    45  // Deprecated: use Load instead.
    46  func LoadConfig(file string, v interface{}, opts ...Option) error {
    47  	return Load(file, v, opts...)
    48  }
    49  
    50  // LoadFromJsonBytes loads config into v from content json bytes.
    51  func LoadFromJsonBytes(content []byte, v interface{}) error {
    52  	return mapping.UnmarshalJsonBytes(content, v)
    53  }
    54  
    55  // LoadConfigFromJsonBytes loads config into v from content json bytes.
    56  // Deprecated: use LoadFromJsonBytes instead.
    57  func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
    58  	return LoadFromJsonBytes(content, v)
    59  }
    60  
    61  // LoadFromTomlBytes loads config into v from content toml bytes.
    62  func LoadFromTomlBytes(content []byte, v interface{}) error {
    63  	return mapping.UnmarshalTomlBytes(content, v)
    64  }
    65  
    66  // LoadFromYamlBytes loads config into v from content yaml bytes.
    67  func LoadFromYamlBytes(content []byte, v interface{}) error {
    68  	return mapping.UnmarshalYamlBytes(content, v)
    69  }
    70  
    71  // LoadConfigFromYamlBytes loads config into v from content yaml bytes.
    72  // Deprecated: use LoadFromYamlBytes instead.
    73  func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
    74  	return LoadFromYamlBytes(content, v)
    75  }
    76  
    77  // MustLoad loads config into v from path, exits on error.
    78  func MustLoad(path string, v interface{}, opts ...Option) {
    79  	if err := Load(path, v, opts...); err != nil {
    80  		log.Fatalf("error: config file %s, %s", path, err.Error())
    81  	}
    82  }