about summary refs log tree commit diff stats
path: root/internal/config/config.go
blob: 96f721eac3f81bf37a9a4cde42bf5031c821fb8a (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package config

import (
	"fmt"
	"io/fs"
	"log/slog"
	"net/url"
	"os"
	"strconv"

	"github.com/BurntSushi/toml"
	"github.com/pkg/errors"
)

type Taxonomy struct {
	Name string
	Feed bool
}

type MenuItem struct {
	Name string
	URL  string `toml:"url"`
}

type URL struct {
	*url.URL
}

func (u *URL) UnmarshalText(text []byte) (err error) {
	u.URL, err = url.Parse(string(text))
	return err
}

type Config struct {
	DefaultLanguage        string `toml:"default_language"`
	BaseURL                URL    `toml:"base_url"`
	RedirectOtherHostnames bool   `toml:"redirect_other_hostnames"`
	Port                   uint64
	Title                  string
	Email                  string
	Description            string
	DomainStartDate        string `toml:"domain_start_date"`
	OriginalDomain         string `toml:"original_domain"`
	Taxonomies             []Taxonomy
	Extra                  struct {
		Headers map[string]string
	}
	Menus map[string][]MenuItem
}

func getEnvFallback(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	} else {
		return fallback
	}
}

func setDevelopmentOverrides(config *Config) error {
	overrideURL, err := URL.Parse(config.BaseURL, "http://localhost:"+fmt.Sprint(config.Port))
	if err != nil {
		return err
	}
	config.BaseURL.URL = overrideURL
	return nil
}

func GetConfig() (*Config, error) {
	config := Config{}
	slog.Debug("reading config.toml")
	_, err := toml.DecodeFile("config.toml", &config)
	if err != nil {
		var pathError *fs.PathError
		var tomlError toml.ParseError
		if errors.As(err, &pathError) {
			return nil, errors.WithMessage(err, "could not read configuration")
		} else if errors.As(err, &tomlError) {
			return nil, errors.WithMessage(err, tomlError.ErrorWithUsage())
		} else {
			return nil, errors.Wrap(err, "config error")
		}
	}
	port, err := strconv.ParseUint(getEnvFallback("PORT", "3000"), 10, 16)
	if err != nil {
		return nil, err
	}
	config.Port = port
	if os.Getenv("ENV") != "production" {
		err = setDevelopmentOverrides(&config)
		if err != nil {
			return nil, errors.WithMessage(err, "could not override configuration")
		}
	}
	return &config, nil
}