Skip to content
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
20 changes: 20 additions & 0 deletions providers/openapi/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,26 @@ func TestResolveEndpoint(t *testing.T) {
require.Equal(t, "application/json", rr.Header().Get("Content-Type"))
},
},
{
name: "base path with parameters",
test: func(t *testing.T, h http.HandlerFunc, c *openapi.Config) {
c.Servers[0].Url = "http://localhost/root"
op := openapitest.NewOperation(
openapitest.WithOperationParam("bar", true),
openapitest.WithResponse(http.StatusOK,
openapitest.WithContent("application/json",
openapitest.NewContent()),
),
)
openapitest.AppendPath("/foo/{bar}", c, openapitest.WithOperation("get", op))

r := httptest.NewRequest("get", "http://localhost/root/foo/bar", nil)
r = r.WithContext(context.WithValue(r.Context(), "servicePath", "/root"))
rr := httptest.NewRecorder()
h(rr, r)
require.Equal(t, http.StatusOK, rr.Code)
},
},
{
// there is no official specification for trailing slash. For ease of use, mokapi considers it equivalent
name: "spec define suffix / but request does not",
Expand Down
15 changes: 14 additions & 1 deletion providers/openapi/parameter/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ func parsePath(param *Parameter, route string, r *http.Request) (*RequestParamet
}

func findPathValue(p *Parameter, route string, r *http.Request) (string, error) {
requestPath := r.URL.Path
if len(requestPath) > 1 {
requestPath = strings.TrimRight(requestPath, "/")
}

servicePath, ok := r.Context().Value("servicePath").(string)
if ok && servicePath != "/" {
requestPath = strings.Replace(requestPath, servicePath, "", 1)
if requestPath == "" {
requestPath = "/"
}
}

// Find all {param} names
re := regexp.MustCompile(`\{([^}]+)\}`)
names := re.FindAllStringSubmatch(route, -1)
Expand All @@ -68,7 +81,7 @@ func findPathValue(p *Parameter, route string, r *http.Request) (string, error)
return "", fmt.Errorf("path parameter %s not found in route %s", p.Name, route)
}

match := re.FindStringSubmatch(r.URL.Path)
match := re.FindStringSubmatch(requestPath)
if match == nil {
// path parameters are always required
return "", fmt.Errorf("url does not match route")
Expand Down
13 changes: 9 additions & 4 deletions providers/openapi/request_body.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,19 @@ package openapi

import (
"fmt"
"gopkg.in/yaml.v3"
"io"
"maps"
"mime/multipart"
"mokapi/config/dynamic"
"mokapi/media"
"mokapi/providers/openapi/schema"
"mokapi/schema/encoding"
"mokapi/schema/json/parser"
"net/http"
"slices"
"strings"

"gopkg.in/yaml.v3"
)

var defaultContentType = media.ParseContentType("application/octet-stream")
Expand Down Expand Up @@ -58,7 +61,7 @@ func BodyFromRequest(r *http.Request, op *Operation) (body *Body, err error) {
contentType := media.ParseContentType(r.Header.Get("content-type"))
_, mt := getMedia(contentType, op.RequestBody.Value)
if !contentType.IsEmpty() && mt == nil {
return noMatch(r, contentType)
return noMatch(r, contentType, op)
}

var b *Body
Expand All @@ -78,12 +81,14 @@ func BodyFromRequest(r *http.Request, op *Operation) (body *Body, err error) {
return b, err
}

func noMatch(r *http.Request, contentType media.ContentType) (*Body, error) {
func noMatch(r *http.Request, contentType media.ContentType, op *Operation) (*Body, error) {
data, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("read request body failed: %w", err)
}
return &Body{Raw: string(data)}, fmt.Errorf("read request body failed: no matching content type for '%v' defined", contentType.String())
supported := slices.Collect(maps.Keys(op.RequestBody.Value.Content))
errHttp := newHttpErrorf(http.StatusUnsupportedMediaType, "Unsupported Content-Type: %s\nThis operation only accepts: %s\nPlease set the Content-Type header to one of the supported types.", contentType.String(), strings.Join(supported, ", "))
return &Body{Raw: string(data)}, errHttp
}

func readBodyDetectContentType(r *http.Request, op *Operation) (*Body, error) {
Expand Down
7 changes: 4 additions & 3 deletions providers/openapi/request_body_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ package openapi_test
import (
"encoding/json"
"fmt"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
"mokapi/providers/openapi"
"mokapi/providers/openapi/openapitest"
"mokapi/providers/openapi/schema/schematest"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
)

type errReader int
Expand Down Expand Up @@ -263,7 +264,7 @@ func TestBodyFromRequest(t *testing.T) {
return r
},
test: func(t *testing.T, result *openapi.Body, err error) {
require.EqualError(t, err, "read request body failed: no matching content type for 'application/xml' defined")
require.EqualError(t, err, "Unsupported Content-Type: application/xml\nThis operation only accepts: application/json\nPlease set the Content-Type header to one of the supported types.")
require.Equal(t, "<root><foo>bar</foo></root>", result.Raw)
},
},
Expand Down
Loading