Skip to content

Commit

Permalink
Use sync.Map like requestBodyValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
k1LoW authored and daveshanley committed Apr 25, 2024
1 parent 6035624 commit 2540a40
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
10 changes: 6 additions & 4 deletions responses/response_body.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
package responses

import (
"net/http"
"sync"

"github.com/pb33f/libopenapi-validator/errors"
"github.com/pb33f/libopenapi/datamodel/high/base"
"github.com/pb33f/libopenapi/datamodel/high/v3"
"net/http"
v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
)

// ResponseBodyValidator is an interface that defines the methods for validating response bodies for Operations.
Expand All @@ -34,7 +36,7 @@ func (v *responseBodyValidator) SetPathItem(path *v3.PathItem, pathValue string)

// NewResponseBodyValidator will create a new ResponseBodyValidator from an OpenAPI 3+ document
func NewResponseBodyValidator(document *v3.Document) ResponseBodyValidator {
return &responseBodyValidator{document: document, schemaCache: make(map[[32]byte]*schemaCache)}
return &responseBodyValidator{document: document, schemaCache: &sync.Map{}}
}

type schemaCache struct {
Expand All @@ -48,5 +50,5 @@ type responseBodyValidator struct {
pathItem *v3.PathItem
pathValue string
errors []*errors.ValidationError
schemaCache map[[32]byte]*schemaCache
schemaCache *sync.Map
}
13 changes: 6 additions & 7 deletions responses/validate_body.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,11 @@ func (v *responseBodyValidator) checkResponseSchema(
// have we seen this schema before? let's hash it and check the cache.
hash := mediaType.GoLow().Schema.Value.Hash()

if cacheHit, ch := v.schemaCache[hash]; ch {

if cacheHit, ch := v.schemaCache.Load(hash); ch {
// got a hit, use cached values
schema = cacheHit.schema
renderedInline = cacheHit.renderedInline
renderedJSON = cacheHit.renderedJSON
schema = cacheHit.(*schemaCache).schema
renderedInline = cacheHit.(*schemaCache).renderedInline
renderedJSON = cacheHit.(*schemaCache).renderedJSON

} else {

Expand All @@ -140,11 +139,11 @@ func (v *responseBodyValidator) checkResponseSchema(
schema = mediaType.Schema.Schema()
renderedInline, _ = schema.RenderInline()
renderedJSON, _ = utils.ConvertYAMLtoJSON(renderedInline)
v.schemaCache[hash] = &schemaCache{
v.schemaCache.Store(hash, &schemaCache{
schema: schema,
renderedInline: renderedInline,
renderedJSON: renderedJSON,
}
})
}

// render the schema, to be used for validation
Expand Down

0 comments on commit 2540a40

Please sign in to comment.