Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add mutex to prevent concurrent map writes #10

Merged
merged 2 commits into from
Oct 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions envi.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,46 @@ import (
"encoding/json"
"fmt"
"os"
"sync"

"github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v2"
)

// Envi is a config loader to load all sorts of configuration files.
type Envi struct {
mu sync.Mutex
loadedVars map[string]string
}

// NewEnvi creates a new Envi instance.
func NewEnvi() *Envi {
return &Envi{
mu: sync.Mutex{},
loadedVars: make(map[string]string),
}
}

// FromMap loads the given key-value pairs and loads them into the local map.
func (envi *Envi) FromMap(vars map[string]string) {
envi.mu.Lock()

for key := range vars {
envi.loadedVars[key] = vars[key]
}

envi.mu.Unlock()
}

// LoadEnv loads the given keys from the environment variables.
func (envi *Envi) LoadEnv(vars ...string) {
envi.mu.Lock()

for _, key := range vars {
envi.loadedVars[key] = os.Getenv(key)
}

envi.mu.Unlock()
}

// LoadYAMLFilesFromEnvPaths loads yaml files from the paths in the given environment variables.
Expand Down Expand Up @@ -99,7 +110,9 @@ func (envi *Envi) LoadFile(key, filePath string) error {
return fmt.Errorf(errMessage, &FailedToReadFileError{filePath})
}

envi.mu.Lock()
envi.loadedVars[key] = string(blob)
envi.mu.Unlock()

return nil
}
Expand Down Expand Up @@ -164,9 +177,13 @@ func (envi *Envi) LoadJSON(blobs ...[]byte) error {
return fmt.Errorf(errMessage, err)
}

envi.mu.Lock()

for key := range decoded {
envi.loadedVars[key] = decoded[key]
}

envi.mu.Unlock()
}

return nil
Expand Down Expand Up @@ -232,9 +249,13 @@ func (envi *Envi) LoadYAML(blobs ...[]byte) error {
return fmt.Errorf(errMessage, err)
}

envi.mu.Lock()

for key := range decoded {
envi.loadedVars[key] = decoded[key]
}

envi.mu.Unlock()
}

return nil
Expand Down