summaryrefslogtreecommitdiff
path: root/config/config.go
blob: 5dfc933c3b9bdbf395844f6259fa3b1f22919836 (plain)
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
package config

import (
	"errors"
	"fmt"
	"github.com/BurntSushi/toml"
	"net/url"
	"os"
)

type Config struct {
	Servers []struct {
		Name   string `toml:"name"`
		Prefix string `toml:"prefix"`
		Proxy  string `toml:"proxy"`
	} `toml:"servers"`
	Debug   bool   `toml:"debug"`
	Listen  string `toml:"listen"`
	Metrics struct {
		Enabled bool `toml:"enabled"`
	} `toml:"metrics"`
}

func (c Config) Validate() error {
	if len(c.Servers) == 0 {
		return errors.New("no yggdrasil server specified")
	}
	for _, s := range c.Servers {
		if s.Prefix == "" {
			return fmt.Errorf("missing prefix for yggdrasil server `%v`", s.Name)
		}
		_, err := url.Parse(s.Prefix)
		if err != nil {
			return fmt.Errorf("invalid prefix for yggdrasil server `%v`: %w", s.Name, err)
		}
	}
	return nil
}

func Read(path string) (*Config, error) {
	f, err := os.Open(path)
	if err != nil {
		return nil, fmt.Errorf("open: %w", err)
	}
	defer func() {
		_ = f.Close()
	}()
	dec := toml.NewDecoder(f)
	var c Config
	_, err = dec.Decode(&c)
	if err != nil {
		return nil, fmt.Errorf("decode: %w", err)
	}
	return &c, nil
}