Skip to content

Commit

Permalink
Try decoding as JSON first then YAML, for speed (#693)
Browse files Browse the repository at this point in the history
Fixes #680
  • Loading branch information
fenollp authored Dec 7, 2022
1 parent ebbf60d commit 8718011
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ jobs:
run: |
! grep -IErn '\s$' --exclude-dir={.git,target,pgdata}
- if: runner.os == 'Linux'
name: Ensure use of unmarshal
run: |
[[ "$(git grep -F yaml. -- openapi3/ | grep -v _test.go | wc -l)" = 1 ]]
- if: runner.os == 'Linux'
name: Missing specification object link to definition
run: |
Expand Down
16 changes: 12 additions & 4 deletions openapi3/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func (loader *Loader) loadSingleElementFromURI(ref string, rootPath *url.URL, el
if err != nil {
return nil, err
}
if err := yaml.Unmarshal(data, element); err != nil {
if err := unmarshal(data, element); err != nil {
return nil, err
}

Expand All @@ -133,7 +133,7 @@ func (loader *Loader) readURL(location *url.URL) ([]byte, error) {
func (loader *Loader) LoadFromData(data []byte) (*T, error) {
loader.resetVisitedPathItemRefs()
doc := &T{}
if err := yaml.Unmarshal(data, doc); err != nil {
if err := unmarshal(data, doc); err != nil {
return nil, err
}
if err := loader.ResolveRefsIn(doc, nil); err != nil {
Expand Down Expand Up @@ -162,7 +162,7 @@ func (loader *Loader) loadFromDataWithPathInternal(data []byte, location *url.UR
doc := &T{}
loader.visitedDocuments[uri] = doc

if err := yaml.Unmarshal(data, doc); err != nil {
if err := unmarshal(data, doc); err != nil {
return nil, err
}
if err := loader.ResolveRefsIn(doc, location); err != nil {
Expand All @@ -172,6 +172,14 @@ func (loader *Loader) loadFromDataWithPathInternal(data []byte, location *url.UR
return doc, nil
}

func unmarshal(data []byte, v interface{}) error {
// See https://github.com/getkin/kin-openapi/issues/680
if err := json.Unmarshal(data, v); err != nil {
return yaml.Unmarshal(data, v)
}
return nil
}

// ResolveRefsIn expands references if for instance spec was just unmarshalled
func (loader *Loader) ResolveRefsIn(doc *T, location *url.URL) (err error) {
if loader.Context == nil {
Expand Down Expand Up @@ -319,7 +327,7 @@ func (loader *Loader) resolveComponent(
if err2 != nil {
return nil, err
}
if err2 = yaml.Unmarshal(data, &cursor); err2 != nil {
if err2 = unmarshal(data, &cursor); err2 != nil {
return nil, err
}
if cursor, err2 = drill(cursor); err2 != nil || cursor == nil {
Expand Down

0 comments on commit 8718011

Please sign in to comment.