Skip to content

Commit

Permalink
feat: add option explode to control how query params are handled.
Browse files Browse the repository at this point in the history
  • Loading branch information
wI2L committed Jan 29, 2019
1 parent 74f1c78 commit 1afc764
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
8 changes: 8 additions & 0 deletions tonic/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,14 @@ func bind(c *gin.Context, v reflect.Value, tag string, extract extractor) error
if tagValue == "" {
continue
}
// Set-up context for extractors.
// Query.
explode, ok := ft.Tag.Lookup(ExplodeTag)
if ok && explode == "false" {
c.Set(ExplodeTag, false)
} else {
c.Set(ExplodeTag, true)
}
_, fieldValues, err := extract(c, tagValue)
if err != nil {
return BindError{field: ft.Name, typ: t, message: err.Error()}
Expand Down
35 changes: 23 additions & 12 deletions tonic/tonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const (
RequiredTag = "required"
DefaultTag = "default"
ValidationTag = "validate"
ExplodeTag = "explode"
)

const (
Expand Down Expand Up @@ -254,27 +255,37 @@ func extractQuery(c *gin.Context, tag string) (string, []string, error) {
if err != nil {
return "", nil, err
}

rawQ := c.Request.URL.Query()[name]

// delete empty elements so default+required will play nice together
// append to a new collection to preserve order without too much copying
q := make([]string, 0, len(rawQ))
for i := range rawQ {
if rawQ[i] != "" {
q = append(q, rawQ[i])
var params []string
query := c.Request.URL.Query()[name]

if c.GetBool(ExplodeTag) {
// Delete empty elements so default and required arguments
// will play nice together. Append to a new collection to
// preserve order without too much copying.
params = make([]string, 0, len(query))
for i := range query {
if query[i] != "" {
params = append(params, query[i])
}
}
} else {
splitFn := func(c rune) bool {
return c == ','
}
if len(query) > 0 {
params = strings.FieldsFunc(query[0], splitFn)
}
}

// XXX: deprecated, use of "default" tag is preferred
if len(q) == 0 && defaultVal != "" {
if len(params) == 0 && defaultVal != "" {
return name, []string{defaultVal}, nil
}
// XXX: deprecated, use of "validate" tag is preferred
if len(q) == 0 && required {
if len(params) == 0 && required {
return "", nil, fmt.Errorf("missing query parameter: %s", name)
}
return name, q, nil
return name, params, nil
}

// extractPath is an extractor that operates on the path
Expand Down

0 comments on commit 1afc764

Please sign in to comment.