Skip to content

Commit

Permalink
add support for resource name in swagger plugin (#702)
Browse files Browse the repository at this point in the history
  • Loading branch information
ch3rub1m authored and johanbrandhorst committed Aug 16, 2018
1 parent fa45a21 commit de0b679
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
15 changes: 14 additions & 1 deletion protoc-gen-swagger/genswagger/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ func templateToSwaggerPath(path string) string {
}
// Pop from the stack
depth--
buffer += "}"
buffer += string(char)
case '/':
if depth == 0 {
parts = append(parts, buffer)
Expand All @@ -534,6 +534,7 @@ func templateToSwaggerPath(path string) string {
// section.
continue
}
buffer += string(char)
default:
buffer += string(char)
break
Expand All @@ -548,12 +549,24 @@ func templateToSwaggerPath(path string) string {
// memory.
re := regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}")
for index, part := range parts {
// If part is a resource name such as "parent", "name", "user.name", the format info must be retained.
prefix := re.ReplaceAllString(part, "$1")
if isResourceName(prefix) {
continue
}
parts[index] = re.ReplaceAllString(part, "{$1}")
}

return strings.Join(parts, "/")
}

func isResourceName(prefix string) bool {
words := strings.Split(prefix, ".")
l := len(words)
field := words[l-1]
return field == "parent" || field == "name"
}

func renderServices(services []*descriptor.Service, paths swaggerPathsObject, reg *descriptor.Registry, requestResponseRefs, customRefs refMap) error {
// Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array.
for svcIdx, svc := range services {
Expand Down
5 changes: 5 additions & 0 deletions protoc-gen-swagger/genswagger/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,11 @@ func TestTemplateToSwaggerPath(t *testing.T) {
{"/{test=prefix/that/has/multiple/parts/to/it/*}", "/{test}"},
{"/{test1}/{test2}", "/{test1}/{test2}"},
{"/{test1}/{test2}/", "/{test1}/{test2}/"},
{"/{name=prefix/*}", "/{name=prefix/*}"},
{"/{name=prefix1/*/prefix2/*}", "/{name=prefix1/*/prefix2/*}"},
{"/{user.name=prefix/*}", "/{user.name=prefix/*}"},
{"/{user.name=prefix1/*/prefix2/*}", "/{user.name=prefix1/*/prefix2/*}"},
{"/{parent=prefix/*}/children", "/{parent=prefix/*}/children"},
}

for _, data := range tests {
Expand Down

0 comments on commit de0b679

Please sign in to comment.