Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework router #210

Merged
merged 5 commits into from
Mar 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 12 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,9 @@ Here's some projects that depend on _kin-openapi_:
* Support for OpenAPI 3 files, including serialization, deserialization, and validation.
* _openapi3filter_ ([godoc](https://godoc.org/github.com/getkin/kin-openapi/openapi3filter))
* Validates HTTP requests and responses
* Provides a [gorilla/mux](https://github.com/gorilla/mux) router for OpenAPI operations
* _openapi3gen_ ([godoc](https://godoc.org/github.com/getkin/kin-openapi/openapi3gen))
* Generates `*openapi3.Schema` values for Go types.
* _pathpattern_ ([godoc](https://godoc.org/github.com/getkin/kin-openapi/pathpattern))
* Matches strings with OpenAPI path patterns ("/path/{parameter}")

# Some recipes
## Loading OpenAPI document
Expand All @@ -51,19 +50,12 @@ swagger, err := openapi3.NewSwaggerLoader().LoadSwaggerFromFile("swagger.json")

## Getting OpenAPI operation that matches request
```go
func GetOperation(httpRequest *http.Request) (*openapi3.Operation, error) {
// Load Swagger file
router := openapi3filter.NewRouter().WithSwaggerFromFile("swagger.json")

// Find route
route, _, err := router.FindRoute("GET", req.URL)
if err != nil {
return nil, err
}

// Get OpenAPI 3 operation
return route.Operation
}
loader := openapi3.NewSwaggerLoader()
spec, _ := loader.LoadSwaggerFromData([]byte(`...`))
_ := spec.Validate(loader.Context)
router, _ := openapi3filter.NewRouter(spec)
route, pathParams, _ := router.FindRoute(httpRequest)
// Do something with route.Operation
```

## Validating HTTP requests/responses
Expand All @@ -81,12 +73,15 @@ import (
)

func main() {
router := openapi3filter.NewRouter().WithSwaggerFromFile("swagger.json")
ctx := context.Background()
loader := &openapi3.SwaggerLoader{Context: ctx}
spec, _ := loader.LoadSwaggerFromFile("openapi3_spec.json")
_ := spec.Validate(ctx)
router, _ := openapi3filter.NewRouter(spec)
httpReq, _ := http.NewRequest(http.MethodGet, "/items", nil)

// Find route
route, pathParams, _ := router.FindRoute(httpReq.Method, httpReq.URL)
route, pathParams, _ := router.FindRoute(httpReq)

// Validate request
requestValidationInput := &openapi3filter.RequestValidationInput{
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.16
require (
github.com/ghodss/yaml v1.0.0
github.com/go-openapi/jsonpointer v0.19.5
github.com/gorilla/mux v1.8.0
github.com/stretchr/testify v1.5.1
gopkg.in/yaml.v2 v2.3.0 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUe
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/swag v0.19.5 h1:lTz6Ys4CmqqCQmZPBlbQENR1/GucA2bzYTE12Pw4tFY=
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
Expand Down
15 changes: 13 additions & 2 deletions openapi3/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package openapi3
import (
"context"
"errors"
"fmt"
"math"
"net/url"
"strings"
Expand Down Expand Up @@ -128,7 +129,17 @@ func (server *Server) Validate(c context.Context) (err error) {
if server.URL == "" {
return errors.New("value of url must be a non-empty string")
}
for _, v := range server.Variables {
opening, closing := strings.Count(server.URL, "{"), strings.Count(server.URL, "}")
if opening != closing {
return errors.New("server URL has mismatched { and }")
}
if opening != len(server.Variables) {
return errors.New("server has undeclared variables")
}
for name, v := range server.Variables {
if !strings.Contains(server.URL, fmt.Sprintf("{%s}", name)) {
return errors.New("server has undeclared variables")
}
if err = v.Validate(c); err != nil {
return
}
Expand All @@ -154,7 +165,7 @@ func (serverVariable *ServerVariable) UnmarshalJSON(data []byte) error {

func (serverVariable *ServerVariable) Validate(c context.Context) error {
switch serverVariable.Default.(type) {
case float64, string:
case float64, string, nil:
default:
return errors.New("value of default must be either a number or a string")
}
Expand Down
35 changes: 33 additions & 2 deletions openapi3/swagger_loader_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package openapi3

import (
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -82,8 +84,8 @@ func TestResolveSchemaRef(t *testing.T) {
doc, err := loader.LoadSwaggerFromData(source)
require.NoError(t, err)
err = doc.Validate(loader.Context)

require.NoError(t, err)

refAVisited := doc.Components.Schemas["A"].Value.AllOf[0]
require.Equal(t, "#/components/schemas/B", refAVisited.Ref)
require.NotNil(t, refAVisited.Value)
Expand Down Expand Up @@ -267,7 +269,6 @@ func TestLoadFileWithExternalSchemaRef(t *testing.T) {
loader.IsExternalRefsAllowed = true
swagger, err := loader.LoadSwaggerFromFile("testdata/testref.openapi.json")
require.NoError(t, err)

require.NotNil(t, swagger.Components.Schemas["AnotherTestSchema"].Value.Type)
}

Expand Down Expand Up @@ -497,3 +498,33 @@ paths:
err = doc.Validate(loader.Context)
require.NoError(t, err)
}

func TestServersVariables(t *testing.T) {
const spec = `
openapi: 3.0.1
info:
title: My API
version: 1.0.0
paths: {}
servers:
- @@@
`
for value, expected := range map[string]error{
`{url: /}`: nil,
`{url: "http://{x}.{y}.example.com"}`: errors.New("invalid servers: server has undeclared variables"),
`{url: "http://{x}.y}.example.com"}`: errors.New("invalid servers: server URL has mismatched { and }"),
`{url: "http://{x.example.com"}`: errors.New("invalid servers: server URL has mismatched { and }"),
`{url: "http://{x}.example.com", variables: {x: {default: "www"}}}`: nil,
`{url: "http://{x}.example.com", variables: {x: {enum: ["www"]}}}`: nil,
`{url: "http://www.example.com", variables: {x: {enum: ["www"]}}}`: errors.New("invalid servers: server has undeclared variables"),
`{url: "http://{y}.example.com", variables: {x: {enum: ["www"]}}}`: errors.New("invalid servers: server has undeclared variables"),
} {
t.Run(value, func(t *testing.T) {
loader := NewSwaggerLoader()
doc, err := loader.LoadSwaggerFromData([]byte(strings.Replace(spec, "@@@", value, 1)))
require.NoError(t, err)
err = doc.Validate(loader.Context)
require.Equal(t, expected, err)
})
}
}
9 changes: 0 additions & 9 deletions openapi3filter/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,6 @@ import (
"github.com/getkin/kin-openapi/openapi3"
)

type RouteError struct {
Route Route
Reason string
}

func (err *RouteError) Error() string {
return err.Reason
}

var _ error = &RequestError{}

// RequestError is returned by ValidateRequest when request does not match OpenAPI spec
Expand Down
7 changes: 4 additions & 3 deletions openapi3filter/req_resp_decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"testing"

"github.com/getkin/kin-openapi/openapi3"
legacyrouter "github.com/getkin/kin-openapi/routers/legacy"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -922,10 +923,10 @@ func TestDecodeParameter(t *testing.T) {
spec.AddOperation(path, http.MethodGet, op)
err = spec.Validate(context.Background())
require.NoError(t, err)
router := NewRouter()
require.NoError(t, router.AddSwagger(spec))
router, err := legacyrouter.NewRouter(spec)
require.NoError(t, err)

route, pathParams, err := router.FindRoute(req.Method, req.URL)
route, pathParams, err := router.FindRoute(req)
require.NoError(t, err)

input := &RequestValidationInput{Request: req, PathParams: pathParams, Route: route}
Expand Down
Loading