From 967f6fdf5c1693d3aa27079b3ae28768fb7356c6 Mon Sep 17 00:00:00 2001 From: Alan Pearce Date: Thu, 9 May 2024 16:24:45 +0200 Subject: feat: make configuration optional --- internal/config/config.go | 41 +++++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 14 deletions(-) (limited to 'internal/config/config.go') diff --git a/internal/config/config.go b/internal/config/config.go index c721424..5b06efa 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ import ( "log/slog" "net/url" "os" + "searchix/internal/file" "github.com/pelletier/go-toml/v2" "github.com/pkg/errors" @@ -24,28 +25,40 @@ func (u *URL) UnmarshalText(text []byte) (err error) { } type Config struct { - BaseURL URL `toml:"base_url"` DataPath string `toml:"data_path"` - CSP *CSP `toml:"content-security-policy"` + CSP CSP `toml:"content-security-policy"` Headers map[string]string } +var defaultConfig = Config{ + DataPath: "./data", + CSP: CSP{ + DefaultSrc: []string{"'self'"}, + }, + Headers: map[string]string{ + "x-content-type-options": "nosniff", + }, +} + func GetConfig() (*Config, error) { - config := Config{} + config := defaultConfig slog.Debug("reading config.toml") - file, err := os.Open("config.toml") - if err != nil { - return nil, errors.WithMessage(err, "error reading configuration") + f, err := os.Open("config.toml") + if err := file.NeedNotExist(err); err != nil { + return nil, errors.Wrap(err, "reading config.toml failed") } - dec := toml.NewDecoder(file) - err = dec.Decode(&config) - if err != nil { - var tomlError toml.DecodeError - if errors.As(err, &tomlError) { - return nil, errors.WithMessage(err, tomlError.Error()) - } + if f != nil { + defer f.Close() + dec := toml.NewDecoder(f) + err = dec.Decode(&config) + if err != nil { + var tomlError toml.DecodeError + if errors.As(err, &tomlError) { + return nil, errors.WithMessage(err, tomlError.Error()) + } - return nil, errors.Wrap(err, "config error") + return nil, errors.Wrap(err, "config error") + } } return &config, nil -- cgit 1.4.1