Skip to content

Commit

Permalink
openapi: Add support for external refs
Browse files Browse the repository at this point in the history
Set IsExternalRefsAllowed to true and provide a ReadFromURIFunc.

Fixes #8067
  • Loading branch information
morysh committed Jun 9, 2023
1 parent 7377970 commit c3c773c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
26 changes: 14 additions & 12 deletions tpl/openapi/openapi3/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,20 @@ servers:
description: Optional server description, e.g. Internal staging server for testing
paths:
/users:
get:
summary: Returns a list of users.
description: Optional extended description in CommonMark or HTML.
responses:
'200': # status code
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string
$ref: ./methods/get.yaml
-- assets/api/methods/get.yaml --
get:
summary: Returns a list of users.
description: Optional extended description in CommonMark or HTML.
responses:
'200': # status code
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string
-- config.toml --
baseURL = 'http://example.com/'
-- layouts/index.html --
Expand Down
24 changes: 23 additions & 1 deletion tpl/openapi/openapi3/openapi3.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ package openapi3
import (
"fmt"
"io"
"io/ioutil"
"net/url"
"strings"

gyaml "github.com/ghodss/yaml"

Expand Down Expand Up @@ -90,7 +93,26 @@ func (ns *Namespace) Unmarshal(r resource.UnmarshableResource) (*OpenAPIDocument
return nil, err
}

err = kopenapi3.NewLoader().ResolveRefsIn(s, nil)
loader := kopenapi3.NewLoader()
loader.IsExternalRefsAllowed = true
loader.ReadFromURIFunc = func(loader *kopenapi3.Loader, url *url.URL) ([]byte, error) {
var relativePath string

if strings.HasPrefix(url.Path, "./") {
relativePath = strings.TrimRightFunc(key, func(r rune) bool { return r != '/' }) + strings.TrimPrefix(url.Path, "./")
} else {
relativePath = url.Path
}

file, err := ns.deps.SourceFilesystems.Assets.Fs.Open(relativePath)
if err != nil {
return nil, err
}

return ioutil.ReadAll(file)
}

err = loader.ResolveRefsIn(s, nil)

return &OpenAPIDocument{T: s}, err
})
Expand Down

0 comments on commit c3c773c

Please sign in to comment.