This repository has been archived by the owner on Jun 12, 2022. It is now read-only.
/
config.go
96 lines (76 loc) · 1.95 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package config
import (
"errors"
"io/ioutil"
"github.com/pengsrc/go-shared/convert"
"gopkg.in/yaml.v2"
"github.com/Xuanwo/xuanzang/constants"
)
// Config contains all config needed by xuanzang.
type Config struct {
Host *string `yaml:"host"`
Port *int `yaml:"port"`
DBPath *string `yaml:"db_path"`
IndexPath *string `yaml:"index_path"`
Dictionary *string `yaml:"dictionary"`
StopTokens *string `yaml:"stop_tokens"`
Source *Source `yaml:"source"`
Logger *Logger `yaml:"logger"`
}
// Source will specify a source for xuanzang.
type Source struct {
Type string `yaml:"type"`
URL string `yaml:"url"`
Duration int `yaml:"duration"`
}
// New will create a new config instance.
func New() *Config {
return &Config{}
}
// LoadFromFilePath loads configuration from a specified local path.
// It returns error if file not found or yaml decode failed.
func (c *Config) LoadFromFilePath(filePath string) error {
cYAML, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
return c.LoadFromContent(cYAML)
}
// LoadFromContent loads configuration from a given bytes.
// It returns error if yaml decode failed.
func (c *Config) LoadFromContent(content []byte) error {
return yaml.Unmarshal(content, c)
}
// Check will check if the config is valid.
func (c *Config) Check() error {
if c.Host == nil {
c.Host = convert.String("localhost")
}
if c.Port == nil {
c.Port = convert.Int(8080)
}
if c.DBPath == nil {
return errors.New("db path is empty")
}
if c.IndexPath == nil {
return errors.New("index path is empty")
}
if c.Source == nil {
return errors.New("source is empty")
}
if c.Dictionary == nil {
return errors.New("dictionary is empty")
}
if c.StopTokens == nil {
return errors.New("stop tokens is empty")
}
// Check logger.
if c.Logger == nil {
c.Logger = &Logger{
Level: constants.DefaultLogLevel,
Output: constants.DefaultLogOutput,
}
}
return nil
}
// TODO: Add check for source.