1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-14 02:33:03 +02:00
kratos/config/file/file.go

81 lines
1.4 KiB
Go
Raw Normal View History

2021-02-17 11:14:47 +02:00
package file
import (
"io"
2021-02-17 11:14:47 +02:00
"os"
"path/filepath"
"strings"
"github.com/go-kratos/kratos/v2/config"
)
var _ config.Source = (*file)(nil)
type file struct {
path string
}
// NewSource new a file source.
func NewSource(path string) config.Source {
return &file{path: path}
}
func (f *file) loadFile(path string) (*config.KeyValue, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
data, err := io.ReadAll(file)
2021-02-17 11:14:47 +02:00
if err != nil {
return nil, err
}
info, err := file.Stat()
if err != nil {
return nil, err
}
return &config.KeyValue{
2021-05-17 15:52:23 +02:00
Key: info.Name(),
Format: format(info.Name()),
Value: data,
2021-02-17 11:14:47 +02:00
}, nil
}
func (f *file) loadDir(path string) (kvs []*config.KeyValue, err error) {
2022-05-20 09:37:28 +02:00
files, err := os.ReadDir(path)
2021-02-17 11:14:47 +02:00
if err != nil {
return nil, err
}
for _, file := range files {
// ignore hidden files
if file.IsDir() || strings.HasPrefix(file.Name(), ".") {
continue
}
2022-05-20 09:37:28 +02:00
kv, err := f.loadFile(filepath.Join(path, file.Name()))
2021-02-17 11:14:47 +02:00
if err != nil {
return nil, err
}
kvs = append(kvs, kv)
}
return
}
func (f *file) Load() (kvs []*config.KeyValue, err error) {
fi, err := os.Stat(f.path)
if err != nil {
return nil, err
}
if fi.IsDir() {
return f.loadDir(f.path)
}
kv, err := f.loadFile(f.path)
if err != nil {
return nil, err
}
return []*config.KeyValue{kv}, nil
}
func (f *file) Watch() (config.Watcher, error) {
return newWatcher(f)
}