go-zero/core/conf/config.go

59 lines
1.4 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package conf
import (
"fmt"
"io/ioutil"
"log"
2020-12-25 11:42:19 +08:00
"os"
2020-07-26 17:09:05 +08:00
"path"
2020-08-08 16:40:10 +08:00
"github.com/tal-tech/go-zero/core/mapping"
2020-07-26 17:09:05 +08:00
)
var loaders = map[string]func([]byte, interface{}) error{
".json": LoadConfigFromJsonBytes,
".yaml": LoadConfigFromYamlBytes,
".yml": LoadConfigFromYamlBytes,
}
2021-02-18 15:56:19 +08:00
// LoadConfig loads config into v from file, .json, .yaml and .yml are acceptable.
func LoadConfig(file string, v interface{}, opts ...Option) error {
content, err := ioutil.ReadFile(file)
if err != nil {
2020-07-26 17:09:05 +08:00
return err
}
loader, ok := loaders[path.Ext(file)]
if !ok {
2021-03-29 23:35:49 +08:00
return fmt.Errorf("unrecognized file type: %s", file)
}
var opt options
for _, o := range opts {
o(&opt)
}
if opt.env {
2020-12-25 11:42:19 +08:00
return loader([]byte(os.ExpandEnv(string(content))), v)
2020-07-26 17:09:05 +08:00
}
2021-02-09 13:50:21 +08:00
return loader(content, v)
2020-07-26 17:09:05 +08:00
}
2021-02-18 15:56:19 +08:00
// LoadConfigFromJsonBytes loads config into v from content json bytes.
2020-07-26 17:09:05 +08:00
func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
return mapping.UnmarshalJsonBytes(content, v)
}
2021-02-18 15:56:19 +08:00
// LoadConfigFromYamlBytes loads config into v from content yaml bytes.
2020-07-26 17:09:05 +08:00
func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
return mapping.UnmarshalYamlBytes(content, v)
}
2021-02-18 15:56:19 +08:00
// MustLoad loads config into v from path, exits on error.
func MustLoad(path string, v interface{}, opts ...Option) {
if err := LoadConfig(path, v, opts...); err != nil {
2020-07-26 17:09:05 +08:00
log.Fatalf("error: config file %s, %s", path, err.Error())
}
}