all repos

moviefeed @ 940d72a

rss feed server for tracking new tv show episodes

moviefeed/config.go(view raw)

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 (
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v2"
)

type Config struct {
	APIKey string   `json:"api_key" yaml:"api_key"`
	Port   string   `json:"port"    yaml:"port"`
	Shows  []string `json:"shows"   yaml:"shows"`
}

func loadConfig(path string) (*Config, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	var config Config

	switch strings.ToLower(filepath.Ext(path)) {
	case ".yaml", ".yml":
		err = yaml.NewDecoder(file).Decode(&config)
	case ".json":
		err = json.NewDecoder(file).Decode(&config)
	default:
		return nil, errors.New("unsupported config file format")
	}

	if err != nil {
		return nil, errors.New("failed to decode config")
	}

	// defaults
	if config.Port == "" {
		config.Port = "8000"
	}

	// validate
	if config.APIKey == "" {
		return nil, errors.New("api_key is required")
	}

	if len(config.Shows) == 0 {
		return nil, errors.New("at least one show must be specified")
	}

	return &config, nil
}