Skip to content

Commit

Permalink
Use once.
Browse files Browse the repository at this point in the history
  • Loading branch information
googollee committed Apr 12, 2024
1 parent 01121f5 commit b62541f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 18 deletions.
24 changes: 7 additions & 17 deletions module/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type providerWithLine struct {
type Repo struct {
providers map[moduleKey]providerWithLine

locker sync.RWMutex // protects filed `instances` below
init sync.Once
instances map[moduleKey]any
}

Expand Down Expand Up @@ -49,22 +49,12 @@ func (r *Repo) Add(provider Provider) {
// Injecting instances only create once if necessary. Calling `InjectTo` mutlple times share instances between returning contexts.
// InjectTo ignores all new providers adding to the Repo after the first run. So adding all providers before calling `InjectTo`.
func (r *Repo) InjectTo(ctx context.Context) (context.Context, error) {
r.locker.RLock()
needCreating := len(r.instances) == 0
r.locker.RUnlock()

if needCreating {
var err error

r.locker.Lock()
if len(r.instances) == 0 {
err = r.buildValues(ctx)
}
r.locker.Unlock()

if err != nil {
return nil, err
}
var err error
r.init.Do(func() {
err = r.buildValues(ctx)
})
if err != nil {
return nil, err
}

return &moduleContext{
Expand Down
2 changes: 1 addition & 1 deletion test.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/bin/sh

GODEBUG=httpmuxgo121=0 go test ./... -v -race
GODEBUG=httpmuxgo121=0 go test -v -race ./...

0 comments on commit b62541f

Please sign in to comment.