Browse Source

Reconfigure config package

master
Matei-Alexandru Gardus 9 months ago
parent
commit
ad125c8cab
No known key found for this signature in database
1 changed files with 33 additions and 16 deletions
  1. 33
    16
      config/config.go

+ 33
- 16
config/config.go View File

@@ -2,44 +2,61 @@ package config
2 2
 
3 3
 import (
4 4
 	"fmt"
5
+	"strings"
5 6
 
6 7
 	"github.com/sirupsen/logrus"
7 8
 	"github.com/spf13/viper"
8 9
 	"github.com/stormfirefox1/GitHookParser/log"
9 10
 )
10 11
 
11
-var v = viper.New()
12
+// Env is a struct that contains all the information for a server to run by getting the configuration necessary for it.
13
+type Env struct {
14
+	config     *viper.Viper
15
+	configPath string
16
+}
17
+
18
+// New returns a config object that can be used by the server struct.
19
+func New(configPath string) Env {
20
+	filePath := strings.Split(configPath, "/")
21
+	configFile := strings.Split(filePath[len(filePath)-1], ".")
22
+	configName := configFile[0]
23
+	configFileType := configFile[1]
12 24
 
13
-func init() {
14
-	v.SetConfigName("config")
15
-	v.SetConfigType("toml")
16
-	v.AddConfigPath("$HOME/.config/git-hook-parser/")
25
+	env := Env{
26
+		config:     viper.New(),
27
+		configPath: configPath,
28
+	}
17 29
 
18
-	// setting up default variables for the whole shebang
30
+	env.config.SetConfigName(configName)
31
+	env.config.SetConfigType(configFileType)
32
+	env.config.AddConfigPath(strings.Join(filePath[:len(filePath)-1], "/"))
33
+
34
+	// setting up default variables for GitHub events (i.e. initial release support)
19 35
 	githubEvents := make([]string, 4)
20 36
 
21 37
 	githubEvents[0] = "push"
22
-	githubEvents[1] = "status"
23
-	githubEvents[2] = "pull_request"
24
-	githubEvents[3] = "issues"
38
+	githubEvents[3] = "ping"
25 39
 
26 40
 	// setting sensible defaults for project config
27
-	v.SetDefault("HANDLER_PORT", ":80")
28
-	v.SetDefault("REDIRECT_URL", "")
29
-	v.SetDefault("GITHUB_EVENTS", githubEvents)
41
+	env.config.SetDefault("HANDLER_PORT", ":80")
42
+	env.config.SetDefault("REDIRECT_URL", "")
43
+	env.config.SetDefault("GITHUB_EVENTS", githubEvents)
44
+	env.config.SetDefault("APP_VERSION", "0.1")
30 45
 
31 46
 	// allowing for override using envvars
32
-	v.AutomaticEnv()
47
+	env.config.AutomaticEnv()
33 48
 
34 49
 	// reading the config file
35
-	err := v.ReadInConfig()
50
+	err := env.config.ReadInConfig()
36 51
 
37 52
 	if err != nil {
38 53
 		log.Fatal(logrus.Fields{}, fmt.Errorf("Fatal error reading configuration file: %v", err))
39 54
 	}
55
+
56
+	return env
40 57
 }
41 58
 
42 59
 // Get will extract a value from the configuration constructs and returns it.
43
-func Get(key string) interface{} {
44
-	return v.Get(key)
60
+func (e *Env) Get(key string) interface{} {
61
+	return e.config.Get(key)
45 62
 }

Loading…
Cancel
Save