Skip to content

Commit

Permalink
fix: don't generate duplicate query decoder functions
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Feb 6, 2023
1 parent b446b64 commit 1124314
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions cmd/happy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ See https://github.com/thnxdev/happy for more information.
didWork = true

gctx := &genContext{
Writer: codewriter.New(pkg.Name),
pkg: pkg,
Writer: codewriter.New(pkg.Name),
pkg: pkg,
haveDecoder: map[string]bool{},
}
gctx.Import("net/http", "io", "encoding/json", "strconv")
for _, svcEndpoints := range endpoints {
Expand Down Expand Up @@ -352,6 +353,10 @@ func genQueryDecoderFunc(gctx *genContext, paramType types.Type) (name string, e
gctx.Import("net/url")
_, typeRef := gctx.TypeRef(paramType)
name = "decode" + ucFirst(strings.ReplaceAll(typeRef, ".", ""))
if gctx.haveDecoder[typeRef] {
return name, nil
}
gctx.haveDecoder[typeRef] = true
w := gctx.Trailer()
w.L("func %s(p url.Values, out *%s) (err error) {", name, typeRef)
w = w.Push()
Expand All @@ -374,6 +379,7 @@ func genQueryDecoderFunc(gctx *genContext, paramType types.Type) (name string, e
w.L("out.%s = new(%s)", field.Name(), fieldType)
strctRef = "*" + strctRef
}
w.Import("fmt")
switch fieldType.String() {
case "time.Duration":
gctx.Import("time")
Expand Down Expand Up @@ -423,6 +429,7 @@ func lcFirst(s string) string {
type genContext struct {
pkg *packages.Package
*codewriter.Writer
haveDecoder map[string]bool
}

func (g *genContext) Pos(pos token.Pos) token.Position {
Expand Down Expand Up @@ -536,7 +543,7 @@ func genEndpoint(gctx *genContext, w *codewriter.Writer, ep endpoint) error {
return fmt.Errorf("%s: %w", pos, err)
}
w.L("if err := %s(r.URL.Query(), &param%d); err != nil {", decoderFn, i)
w.L(` http.Error(w, fmt.Sprintf("Failed to decode query parameters: %%s", err), http.StatusBadRequest)`)
w.L(` http.Error(w, err.Error(), http.StatusBadRequest)`)
w.L(" return")
w.L("}")
} else {
Expand Down

0 comments on commit 1124314

Please sign in to comment.