From eb8dd3ad35829f7dded05e8683ffeda3a33f5f34 Mon Sep 17 00:00:00 2001 From: Elara Musayelyan Date: Fri, 6 Oct 2023 15:07:19 -0700 Subject: [PATCH] Make config thread safe --- internal/config/config.go | 9 ++++++++- internal/config/lang.go | 4 ++++ internal/config/paths.go | 9 ++++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 29aa1ea..89bdc64 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -21,6 +21,7 @@ package config import ( "context" "os" + "sync" "github.com/pelletier/go-toml/v2" "go.elara.ws/lure/internal/types" @@ -39,13 +40,19 @@ var defaultConfig = &types.Config{ }, } -var config *types.Config +var ( + configMtx sync.Mutex + config *types.Config +) // Config returns a LURE configuration struct. // The first time it's called, it'll load the config from a file. // Subsequent calls will just return the same value. func Config(ctx context.Context) *types.Config { + configMtx.Lock() + defer configMtx.Unlock() log := loggerctx.From(ctx) + if config == nil { cfgFl, err := os.Open(GetPaths(ctx).ConfigPath) if err != nil { diff --git a/internal/config/lang.go b/internal/config/lang.go index 9603621..698501e 100644 --- a/internal/config/lang.go +++ b/internal/config/lang.go @@ -22,12 +22,14 @@ import ( "context" "os" "strings" + "sync" "go.elara.ws/lure/pkg/loggerctx" "golang.org/x/text/language" ) var ( + langMtx sync.Mutex lang language.Tag langSet bool ) @@ -37,6 +39,8 @@ var ( // the $LANG environment variable. // Subsequent calls will just return the same value. func Language(ctx context.Context) language.Tag { + langMtx.Lock() + defer langMtx.Unlock() log := loggerctx.From(ctx) if !langSet { syslang := SystemLang() diff --git a/internal/config/paths.go b/internal/config/paths.go index d057166..82cc0b8 100644 --- a/internal/config/paths.go +++ b/internal/config/paths.go @@ -22,6 +22,7 @@ import ( "context" "os" "path/filepath" + "sync" "github.com/pelletier/go-toml/v2" "go.elara.ws/lure/pkg/loggerctx" @@ -37,13 +38,19 @@ type Paths struct { DBPath string } -var paths *Paths +var ( + pathsMtx sync.Mutex + paths *Paths +) // GetPaths returns a Paths struct. // The first time it's called, it'll generate the struct // using information from the system. // Subsequent calls will return the same value. func GetPaths(ctx context.Context) *Paths { + pathsMtx.Lock() + defer pathsMtx.Unlock() + log := loggerctx.From(ctx) if paths == nil { paths = &Paths{}