Merge pull request #994 from abperiasamy/contentdb-race

fixes race in Init
master
Anand Babu (AB) Periasamy 9 years ago
commit bed528d569
  1. 33
      pkg/contentdb/contentdb.go

@ -19,13 +19,18 @@
package contentdb package contentdb
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"sync"
"encoding/json" "encoding/json"
) )
var ( var (
// Internal lock.
mutex = &sync.Mutex{}
// Make note of initialization. // Make note of initialization.
isInitialized = false isInitialized = false
@ -78,20 +83,26 @@ func loadDB() error {
// Init initializes contentdb for lookups. JSON structure is parsed into a simple map of extension and content-type. // Init initializes contentdb for lookups. JSON structure is parsed into a simple map of extension and content-type.
func Init() error { func Init() error {
var e error mutex.Lock()
extDB = make(map[string]string) defer mutex.Unlock()
if !isInitialized { if !isInitialized {
e = loadDB() var e error
extDB = make(map[string]string)
if !isInitialized {
e = loadDB()
}
isInitialized = true
return e
} }
isInitialized = true return nil
return e
} }
// Lookup returns matching content-type for known types of file extensions. // Lookup returns matching content-type for known types of file extensions.
func Lookup(extension string) (contentType string, e error) { func Lookup(extension string) (contentType string, e error) {
if !isInitialized { if !isInitialized {
e = Init() return "", errors.New("contentdb is not initialized.")
} }
return extDB[extension], e return extDB[extension], e
@ -99,11 +110,9 @@ func Lookup(extension string) (contentType string, e error) {
// MustLookup returns matching content-type for known types of file extensions. In case of error, it panics. // MustLookup returns matching content-type for known types of file extensions. In case of error, it panics.
func MustLookup(extension string) (contentType string) { func MustLookup(extension string) (contentType string) {
if !isInitialized { var e error
if e := Init(); e != nil { if contentType, e = Lookup(extension); e != nil {
panic(fmt.Sprintf("Error loading contentdb: %s\n", e)) panic(fmt.Sprintf("Lookup failed: %s\n", e))
}
} }
return contentType
return extDB[extension]
} }

Loading…
Cancel
Save