@@ -2,10 +2,15 @@ package config
2
2
3
3
import (
4
4
"bytes"
5
- "gopkg.in/yaml.v2"
5
+ "errors"
6
+ "fmt"
6
7
"io/ioutil"
7
8
"os"
8
9
"path"
10
+ "strconv"
11
+ "strings"
12
+
13
+ "gopkg.in/yaml.v2"
9
14
)
10
15
11
16
// The configuration of the CLI
@@ -34,7 +39,7 @@ func createDefaultConfiguration() *Config {
34
39
Server : struct {
35
40
Port int `yaml:"port"`
36
41
}{
37
- Port : 12 ,
42
+ Port : 1200 ,
38
43
},
39
44
Lang : struct {
40
45
Default string `yaml:"default"`
@@ -49,14 +54,14 @@ func createDefaultConfiguration() *Config {
49
54
// This function is called when the configuration file does not exist already
50
55
// This will create the configuration file in the user config dir, with a minimalistic
51
56
// default configuration
52
- func saveDefaultConfiguration ( ) error {
57
+ func SaveConfiguration ( config * Config ) error {
53
58
location , err := getDefaultConfigLocation ()
54
59
if err != nil {
55
60
return err
56
61
}
57
62
var buffer bytes.Buffer
58
63
encoder := yaml .NewEncoder (& buffer )
59
- err = encoder .Encode (createDefaultConfiguration () )
64
+ err = encoder .Encode (config )
60
65
if err != nil {
61
66
return err
62
67
}
@@ -89,10 +94,25 @@ func LoadDefaultConfiguration() (*Config, error) {
89
94
}
90
95
if _ , err := os .Stat (location ); err != nil {
91
96
if os .IsNotExist (err ) {
92
- if err := saveDefaultConfiguration (); err != nil {
97
+ config := createDefaultConfiguration ()
98
+ if err := SaveConfiguration (config ); err != nil {
93
99
return nil , err
94
100
}
95
101
}
96
102
}
97
103
return LoadConfiguration (location )
98
104
}
105
+
106
+ // Gets the configuration value associated with the given key
107
+ func GetConfigurationValue (config * Config , key string ) (string , error ) {
108
+ lowerKey := strings .ToLower (key )
109
+ if lowerKey == "server.port" {
110
+ return strconv .Itoa (config .Server .Port ), nil
111
+ } else if lowerKey == "lang.default" {
112
+ return config .Lang .Default , nil
113
+ } else if lowerKey == "author" {
114
+ return config .Author , nil
115
+ } else {
116
+ return "" , errors .New (fmt .Sprintf ("Unknown config key %s" , key ))
117
+ }
118
+ }
0 commit comments