From 2540a402417c8cb841ba4407b34e99a0ce7a607e Mon Sep 17 00:00:00 2001 From: k1LoW Date: Tue, 23 Apr 2024 14:07:38 +0900 Subject: [PATCH] Use sync.Map like requestBodyValidator --- responses/response_body.go | 10 ++++++---- responses/validate_body.go | 13 ++++++------- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/responses/response_body.go b/responses/response_body.go index c54ac08..923fac5 100644 --- a/responses/response_body.go +++ b/responses/response_body.go @@ -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. @@ -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 { @@ -48,5 +50,5 @@ type responseBodyValidator struct { pathItem *v3.PathItem pathValue string errors []*errors.ValidationError - schemaCache map[[32]byte]*schemaCache + schemaCache *sync.Map } diff --git a/responses/validate_body.go b/responses/validate_body.go index 69e611f..017d1d5 100644 --- a/responses/validate_body.go +++ b/responses/validate_body.go @@ -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 { @@ -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