Skip to content

Commit 4502d66

Browse files
committed
Addressed sync issues in #23
Moved to a `sync.Map` Signed-off-by: Dave Shanley <[email protected]>
1 parent 94b058e commit 4502d66

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

requests/request_body.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"github.com/pb33f/libopenapi/datamodel/high/base"
99
"github.com/pb33f/libopenapi/datamodel/high/v3"
1010
"net/http"
11+
"sync"
1112
)
1213

1314
// RequestBodyValidator is an interface that defines the methods for validating request bodies for Operations.
@@ -29,7 +30,7 @@ type RequestBodyValidator interface {
2930

3031
// NewRequestBodyValidator will create a new RequestBodyValidator from an OpenAPI 3+ document
3132
func NewRequestBodyValidator(document *v3.Document) RequestBodyValidator {
32-
return &requestBodyValidator{document: document, schemaCache: make(map[[32]byte]*schemaCache)}
33+
return &requestBodyValidator{document: document, schemaCache: &sync.Map{}}
3334
}
3435

3536
func (v *requestBodyValidator) SetPathItem(path *v3.PathItem, pathValue string) {
@@ -48,5 +49,5 @@ type requestBodyValidator struct {
4849
pathItem *v3.PathItem
4950
pathValue string
5051
errors []*errors.ValidationError
51-
schemaCache map[[32]byte]*schemaCache
52+
schemaCache *sync.Map
5253
}

requests/validate_body.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,11 @@ func (v *requestBodyValidator) ValidateRequestBody(request *http.Request) (bool,
6464
hash := mediaType.GoLow().Schema.Value.Hash()
6565

6666
// perform work only once and cache the result in the validator.
67-
if cacheHit, ch := v.schemaCache[hash]; ch {
67+
if cacheHit, ch := v.schemaCache.Load(hash); ch {
6868
// got a hit, use cached values
69-
schema = cacheHit.schema
70-
renderedInline = cacheHit.renderedInline
71-
renderedJSON = cacheHit.renderedJSON
69+
schema = cacheHit.(*schemaCache).schema
70+
renderedInline = cacheHit.(*schemaCache).renderedInline
71+
renderedJSON = cacheHit.(*schemaCache).renderedJSON
7272

7373
} else {
7474

@@ -77,11 +77,11 @@ func (v *requestBodyValidator) ValidateRequestBody(request *http.Request) (bool,
7777
schema = mediaType.Schema.Schema()
7878
renderedInline, _ = schema.RenderInline()
7979
renderedJSON, _ = utils.ConvertYAMLtoJSON(renderedInline)
80-
v.schemaCache[hash] = &schemaCache{
80+
v.schemaCache.Store(hash, &schemaCache{
8181
schema: schema,
8282
renderedInline: renderedInline,
8383
renderedJSON: renderedJSON,
84-
}
84+
})
8585
}
8686

8787
// render the schema, to be used for validation

0 commit comments

Comments
 (0)