Skip to content

Commit

Permalink
feat: support query:"<name>" tag
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Feb 6, 2023
1 parent 1da7200 commit 9c9b978
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 6 deletions.
8 changes: 8 additions & 0 deletions cmd/happy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"unicode/utf8"

"github.com/alecthomas/kong"
"github.com/fatih/structtag"
"golang.org/x/tools/go/packages"

"github.com/thnxdev/happy/codewriter"
Expand Down Expand Up @@ -351,7 +352,14 @@ func genQueryDecoderFunc(gctx *genContext, paramType types.Type) (name string, e
w = w.Push()
for i := 0; i < strct.NumFields(); i++ {
field := strct.Field(i)
tags, err := structtag.Parse(strct.Tag(i))
if err != nil {
return "", fmt.Errorf("invalid struct tag on %s.%s: %w", typeRef, field.Name(), err)
}
fieldName := lcFirst(field.Name())
if tag, err := tags.Get("query"); err == nil {
fieldName = tag.Name
}
w.L("if q, ok := p[%q]; ok {", fieldName)
w = w.Push()
fieldType := field.Type()
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.19

require (
github.com/alecthomas/kong v0.7.1
github.com/fatih/structtag v1.2.0
golang.org/x/tools v0.3.0
)

Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ github.com/alecthomas/kong v0.7.1 h1:azoTh0IOfwlAX3qN9sHWTxACE2oV8Bg2gAwBsMwDQY4
github.com/alecthomas/kong v0.7.1/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U=
github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE=
github.com/alecthomas/repr v0.1.0/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8=
github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA=
Expand Down
4 changes: 2 additions & 2 deletions testdata/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ func (s *Service) CreateUser(r *http.Request, user User) error {
}

type Paginate struct {
Page int
Size int
Page int `query:"p"`
Size int `query:"s"`
Sparse *bool
}

Expand Down
8 changes: 4 additions & 4 deletions testdata/main_api.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 9c9b978

Please sign in to comment.