Skip to content

Commit 5c9e449

Browse files
authored
Generator: whenever possible favor POST method if GET and POST are available (#268)
1 parent 5c3b976 commit 5c9e449

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

internal/build/cmd/generate/commands/gensource/generator.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -491,7 +491,6 @@ func (r ` + g.Endpoint.MethodWithNamespace() + `Request) Do(ctx context.Context,
491491
params map[string]string
492492
)` + "\n\n")
493493

494-
// Generate the HTTP method
495494
switch g.Endpoint.Name {
496495
case "index":
497496
g.w("\t")
@@ -502,7 +501,16 @@ func (r ` + g.Endpoint.MethodWithNamespace() + `Request) Do(ctx context.Context,
502501
}`)
503502
g.w("\n\n")
504503
default:
505-
g.w("\t" + `method = "` + g.Endpoint.URL.Paths[0].Methods[0] + `"` + "\n\n")
504+
var httpMethod string
505+
// If endpoint has both GET and POST available
506+
// Prefer POST usage in order to prevent go routine leak
507+
// See https://github.com/golang/go/issues/29246
508+
if g.Endpoint.URL.ContainsMethods("GET", "POST") {
509+
httpMethod = "POST"
510+
} else {
511+
httpMethod = g.Endpoint.URL.Paths[0].Methods[0]
512+
}
513+
g.w("\t" + `method = "` + httpMethod + `"` + "\n\n")
506514
}
507515

508516
// Get default part values for specific APIs

internal/build/cmd/generate/commands/gensource/model.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,3 +510,28 @@ func (p *MethodArgument) GoName() string {
510510
func (p *MethodArgument) GoType(comment ...bool) string {
511511
return utils.TypeToGo(p.Type)
512512
}
513+
514+
// ContainsMethods return true if every method passed in argument is present in every Path
515+
func (u *URL) ContainsMethods(methods ...string) bool {
516+
for _, path := range u.Paths {
517+
// Fast exit if both collections are not the same size
518+
if len(methods) != len(path.Methods) {
519+
return false
520+
}
521+
522+
// We iterate over every items
523+
items := make(map[string]struct{})
524+
for _, v := range path.Methods {
525+
items[v] = struct{}{}
526+
}
527+
528+
for _, method := range methods {
529+
if _, ok := items[method]; ok {
530+
continue
531+
}
532+
return false
533+
}
534+
continue
535+
}
536+
return true
537+
}

0 commit comments

Comments
 (0)