internal/config/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 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 | package config
import (
"io/fs"
"net/url"
"path/filepath"
"time"
"go.alanpearce.eu/x/log"
"github.com/BurntSushi/toml"
"gitlab.com/tozd/go/errors"
)
type Taxonomy struct {
Name string
Feed bool
}
type MenuItem struct {
Name string
URL URL `toml:"url"`
}
type URL struct {
*url.URL
}
func NewURL(rawURL string) URL {
u, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
return URL{u}
}
func (u *URL) UnmarshalText(text []byte) (err error) {
u.URL, err = url.Parse(string(text))
return errors.WithMessagef(err, "could not parse URL %s", string(text))
}
type Timezone struct {
*time.Location
}
func (t *Timezone) UnmarshalText(text []byte) (err error) {
t.Location, err = time.LoadLocation(string(text))
return errors.WithMessagef(err, "could not parse timezone %s", string(text))
}
type Config struct {
Title string
Email string
Description string
BaseURL URL `toml:"base_url"`
OriginalDomain string `toml:"original_domain"`
DomainStartDate string `toml:"domain_start_date"`
GoatCounter URL `toml:"goatcounter"`
OIDCHost URL `toml:"oidc_host"`
Domains []string
WildcardDomain string `toml:"wildcard_domain"`
Language string
Timezone Timezone
Taxonomies []Taxonomy
Menu []MenuItem
RelMe []MenuItem `toml:"rel_me"`
}
func GetConfig(dir string, log *log.Logger) (*Config, errors.E) {
config := &Config{}
filename := filepath.Join(dir, "config.toml")
log.Debug("reading config", "filename", filename)
_, err := toml.DecodeFile(filename, config)
if err != nil {
switch t := err.(type) {
case *fs.PathError:
return nil, errors.WithMessage(t, "could not read configuration")
case *toml.ParseError:
return nil, errors.WithMessage(t, t.ErrorWithUsage())
}
return nil, errors.WithMessage(err, "config error")
}
return config, nil
}
|