Skip to content

Commit

Permalink
Merge pull request xeipuuv#133 from johandorland/master
Browse files Browse the repository at this point in the history
Make formatErrorDescription thread-safe
  • Loading branch information
xeipuuv authored Dec 31, 2016
2 parents 59f99eb + 503fefc commit 5760b62
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,18 @@ package gojsonschema

import (
"bytes"
"sync"
"text/template"
)

var errorTemplates *template.Template
var errorTemplates errorTemplate = errorTemplate{template.New("errors-new"),sync.RWMutex{}}

// template.Template is not thread-safe for writing, so some locking is done
// sync.RWMutex is used for efficiently locking when new templates are created
type errorTemplate struct {
*template.Template
sync.RWMutex
}

type (
// RequiredError. ErrorDetails: property string
Expand Down Expand Up @@ -241,14 +249,17 @@ func formatErrorDescription(s string, details ErrorDetails) string {
var descrAsBuffer bytes.Buffer
var err error

if errorTemplates == nil {
errorTemplates = template.New("all-errors")
}

errorTemplates.RLock()
tpl = errorTemplates.Lookup(s)
errorTemplates.RUnlock()

if tpl == nil {
errorTemplates.Lock()
tpl = errorTemplates.New(s)

tpl, err = tpl.Parse(s)
errorTemplates.Unlock()

if err != nil {
return err.Error()
}
Expand Down

0 comments on commit 5760b62

Please sign in to comment.