github.com/shuguocloud/go-zero@v1.3.0/core/conf/config.go (about)

     1  package conf
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"log"
     7  	"os"
     8  	"path"
     9  
    10  	"github.com/shuguocloud/go-zero/core/mapping"
    11  )
    12  
    13  var loaders = map[string]func([]byte, interface{}) error{
    14  	".json": LoadConfigFromJsonBytes,
    15  	".yaml": LoadConfigFromYamlBytes,
    16  	".yml":  LoadConfigFromYamlBytes,
    17  }
    18  
    19  // LoadConfig loads config into v from file, .json, .yaml and .yml are acceptable.
    20  func LoadConfig(file string, v interface{}, opts ...Option) error {
    21  	content, err := ioutil.ReadFile(file)
    22  	if err != nil {
    23  		return err
    24  	}
    25  
    26  	loader, ok := loaders[path.Ext(file)]
    27  	if !ok {
    28  		return fmt.Errorf("unrecognized file type: %s", file)
    29  	}
    30  
    31  	var opt options
    32  	for _, o := range opts {
    33  		o(&opt)
    34  	}
    35  
    36  	if opt.env {
    37  		return loader([]byte(os.ExpandEnv(string(content))), v)
    38  	}
    39  
    40  	return loader(content, v)
    41  }
    42  
    43  // LoadConfigFromJsonBytes loads config into v from content json bytes.
    44  func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
    45  	return mapping.UnmarshalJsonBytes(content, v)
    46  }
    47  
    48  // LoadConfigFromYamlBytes loads config into v from content yaml bytes.
    49  func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
    50  	return mapping.UnmarshalYamlBytes(content, v)
    51  }
    52  
    53  // MustLoad loads config into v from path, exits on error.
    54  func MustLoad(path string, v interface{}, opts ...Option) {
    55  	if err := LoadConfig(path, v, opts...); err != nil {
    56  		log.Fatalf("error: config file %s, %s", path, err.Error())
    57  	}
    58  }