~gjabell/mfn

ref: fd0ff9537d1966e674a35e898687396355ca8be1 mfn/config.go -rw-r--r-- 1.2 KiB
fd0ff953Galen Abell Rename to mfn and refactor config 1 year, 7 months ago
                                                                                
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
package main

import (
	"fmt"
	"html/template"

	"github.com/BurntSushi/toml"
)

type config struct {
	Server             string             `toml:"server"`
	Username           string             `toml:"username"`
	Password           string             `toml:"password"`
	DbPath             string             `toml:"db_path"`
	WebhookTemplateStr string             `toml:"webhook_template"`
	WebhookTemplate    *template.Template `toml:"-"`
	WebhookURL         string             `toml:"webhook_url"`
}

func loadConfig(configPath string) (*config, error) {
	var c config

	if _, err := toml.DecodeFile(configPath, &c); err != nil {
		return nil, err
	}

	if err := c.validate(); err != nil {
		return nil, err
	}

	return &c, nil
}

func (c *config) validate() error {
	for k, v := range map[string]string{
		"server url":       c.Server,
		"username":         c.Username,
		"password":         c.Password,
		"database path":    c.DbPath,
		"webhook template": c.WebhookTemplateStr,
		"webhook url":      c.WebhookURL,
	} {
		if v == "" {
			return fmt.Errorf("you must provide a valid %s", k)
		}
	}

	// parse the template
	tmpl, err := template.New("webhook").Parse(c.WebhookTemplateStr)
	if err != nil {
		return err
	}
	c.WebhookTemplate = tmpl

	return nil
}