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

lazy init global #58

Merged
merged 1 commit into from
Nov 14, 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
20 changes: 18 additions & 2 deletions global.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import (
"log/slog"
"reflect"
"sync"

"github.com/ktong/konf/provider/env"
)
Expand All @@ -16,7 +17,7 @@
// The path is case-insensitive.
func Get[T any](path string) T { //nolint:ireturn
var value T
if err := global.Unmarshal(path, &value); err != nil {
if err := Unmarshal(path, &value); err != nil {
slog.Error(
"Could not read config, return empty value instead.",
"error", err,
Expand All @@ -35,6 +36,8 @@
//
// The path is case-insensitive.
func Unmarshal(path string, target any) error {
initIfNecessary()

return global.Unmarshal(path, target)
}

Expand All @@ -43,6 +46,7 @@
//
// It requires Watch has been called.
func OnChange(onChange func(), paths ...string) {
initIfNecessary()

Check warning on line 49 in global.go

View check run for this annotation

Codecov / codecov/patch

global.go#L49

Added line #L49 was not covered by tests
global.OnChange(func(Unmarshaler) { onChange() }, paths...)
}

Expand All @@ -55,4 +59,16 @@
global = config
}

var global, _ = New(WithLoader(env.New())) //nolint:gochecknoglobals
func initIfNecessary() {
globalOnce.Do(func() {
if reflect.ValueOf(global).IsZero() {
global, _ = New(WithLoader(env.New()))
}

Check warning on line 66 in global.go

View check run for this annotation

Codecov / codecov/patch

global.go#L65-L66

Added lines #L65 - L66 were not covered by tests
})
}

//nolint:gochecknoglobals
var (
global Config
globalOnce sync.Once
)
Loading