From 0cee1c5f942bde5f1003d82665317ab34aed3b4b Mon Sep 17 00:00:00 2001 From: Phenix66 <34311559+Phenix66@users.noreply.github.com> Date: Fri, 7 Jul 2023 03:21:02 -0400 Subject: [PATCH] fix required params parsing for routes with multiple paths and multiple params (#1621) * fix required params parsing for routes with multiple paths and multiple params * fix incorrect variable declaration of validParams --- parser.go | 16 +++++++++++++++- parser_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/parser.go b/parser.go index 2e453960a..5cb00f843 100644 --- a/parser.go +++ b/parser.go @@ -975,7 +975,21 @@ func processRouterOperation(parser *Parser, operation *Operation) error { parser.debug.Printf("warning: %s\n", err) } - *op = &operation.Operation + if len(operation.RouterProperties) > 1 { + newOp := *operation + var validParams []spec.Parameter + for _, param := range newOp.Operation.OperationProps.Parameters { + if param.In == "path" && !strings.Contains(routeProperties.Path, param.Name) { + // This path param is not actually contained in the path, skip adding it to the final params + continue + } + validParams = append(validParams, param) + } + newOp.Operation.OperationProps.Parameters = validParams + *op = &newOp.Operation + } else { + *op = &operation.Operation + } parser.swagger.Paths.Paths[routeProperties.Path] = pathItem } diff --git a/parser_test.go b/parser_test.go index 71dc90da4..55b287d6f 100644 --- a/parser_test.go +++ b/parser_test.go @@ -2905,6 +2905,40 @@ func Test3(){ assert.NotNil(t, val.Delete) } +func TestParser_ParseRouterApiMultiplePathsWithMultipleParams(t *testing.T) { + t.Parallel() + + src := ` +package test + +// @Success 200 +// @Param group_id path int true "Group ID" +// @Param user_id path int true "User ID" +// @Router /examples/groups/{group_id}/user/{user_id}/address [get] +// @Router /examples/user/{user_id}/address [get] +func Test(){ +} +` + p := New() + err := p.packages.ParseFile("api", "api/api.go", src, ParseAll) + assert.NoError(t, err) + + err = p.packages.RangeFiles(p.ParseRouterAPIInfo) + assert.NoError(t, err) + + ps := p.swagger.Paths.Paths + + val, ok := ps["/examples/groups/{group_id}/user/{user_id}/address"] + + assert.True(t, ok) + assert.Equal(t, 2, len(val.Get.Parameters)) + + val, ok = ps["/examples/user/{user_id}/address"] + + assert.True(t, ok) + assert.Equal(t, 1, len(val.Get.Parameters)) +} + // func TestParseDeterministic(t *testing.T) { // mainAPIFile := "main.go" // for _, searchDir := range []string{