Skip to content

Commit

Permalink
make providers map concurrent safe (#521)
Browse files Browse the repository at this point in the history
  • Loading branch information
verygoodsoftwarenotvirus authored Jan 14, 2025
1 parent 0629733 commit b1c5727
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net/http"
"sync"

"golang.org/x/oauth2"
)
Expand All @@ -23,15 +24,21 @@ type Provider interface {

const NoAuthUrlErrorMessage = "an AuthURL has not been set"

// Providers is list of known/available providers.
// Providers is the list of known/available providers.
type Providers map[string]Provider

var providers = Providers{}
var (
providersHat sync.RWMutex
providers = Providers{}
)

// UseProviders adds a list of available providers for use with Goth.
// Can be called multiple times. If you pass the same provider more
// than once, the last will be used.
func UseProviders(viders ...Provider) {
providersHat.Lock()
defer providersHat.Unlock()

for _, provider := range viders {
providers[provider.Name()] = provider
}
Expand All @@ -45,7 +52,9 @@ func GetProviders() Providers {
// GetProvider returns a previously created provider. If Goth has not
// been told to use the named provider it will return an error.
func GetProvider(name string) (Provider, error) {
providersHat.RLock()
provider := providers[name]
providersHat.RUnlock()
if provider == nil {
return nil, fmt.Errorf("no provider for %s exists", name)
}
Expand All @@ -55,6 +64,9 @@ func GetProvider(name string) (Provider, error) {
// ClearProviders will remove all providers currently in use.
// This is useful, mostly, for testing purposes.
func ClearProviders() {
providersHat.Lock()
defer providersHat.Unlock()

providers = Providers{}
}

Expand Down

0 comments on commit b1c5727

Please sign in to comment.