Repository navigation
Expand file tree
/
Copy pathquerystring.go
More file actions
267 lines (226 loc) · 7.82 KB
/
Copy pathquerystring.go
File metadata and controls
267 lines (226 loc) · 7.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2026 Company.info B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package reqbind
import (
"errors"
"fmt"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// queryStringPattern defines the regex pattern for matching bracket-notation query strings.
var queryStringPattern = regexp.MustCompile(`(?P<key>\w+)(?P<innerKeys>(\[[a-zA-Z]+])+)$`)
var (
// ErrMalformedQueryString is returned when the query string has an invalid structure (e.g. mismatched brackets).
ErrMalformedQueryString = errors.New("invalid query string")
// ErrEmptyQueryParam is returned when an empty query parameter is encountered.
ErrEmptyQueryParam = errors.New("empty query param")
)
// ParsedQueryString represents a parsed and categorized query string parameter.
type ParsedQueryString struct {
Key string
InnerKeys []string
Values []string
}
// decodeQueryParams converts query string parameters into the given struct.
func decodeQueryParams(query url.Values, target any) error {
for key, value := range query {
if err := parseAndBind(key, value, target); err != nil {
return err
}
}
return nil
}
// parseAndBind parses a query string key-value pair and binds it to the target struct.
func parseAndBind(key string, value any, target any) error {
pqs, err := parseQueryString(key, value)
if err != nil {
return err
}
return parsedQueryToStruct(pqs, target)
}
// parseQueryString parses a query string key based on bracket notation.
func parseQueryString(key string, value any) (*ParsedQueryString, error) {
pqs := &ParsedQueryString{}
// Check if it is a nested query string with bracket notation.
if strings.Contains(key, "[") || strings.Contains(key, "]") {
if !queryStringPattern.MatchString(key) {
return nil, ErrMalformedQueryString
}
// Extract the key and nested path.
parsed := make(map[string]string)
matched := queryStringPattern.FindStringSubmatch(key)
for index, name := range queryStringPattern.SubexpNames() {
if index != 0 {
parsed[name] = matched[index]
}
}
// Parse the inner keys from the bracket notation.
innerKeys, err := extractInnerKeys(parsed["innerKeys"])
if err != nil {
return nil, err
}
pqs.Key = parsed["key"]
pqs.InnerKeys = innerKeys
} else {
// Simple query string without bracket notation.
pqs.Key = key
}
// Parse value.
//lint:ignore S1034 switch case is much cleaner than if/else here.
switch value.(type) {
case string:
pqs.Values = strings.Split(value.(string), ",")
case []string:
pqs.Values = value.([]string)
}
return pqs, nil
}
// extractInnerKeys parses the nested part of the query string and extracts the inner keys.
// For example, it parses [company][id] and returns [company, id] as the inner keys.
func extractInnerKeys(input string) ([]string, error) {
if len(input) == 0 {
return nil, ErrEmptyQueryParam
}
result := make([]string, 0)
fieldName := ""
// Iterate over characters and extract field names between brackets.
for _, c := range input {
if string(c) == "[" {
continue
}
if string(c) == "]" {
if len(fieldName) == 0 {
return nil, ErrMalformedQueryString
}
result = append(result, fieldName)
fieldName = ""
continue
}
fieldName = fieldName + string(c)
}
return result, nil
}
// parsedQueryToStruct converts a parsed query string into the target struct fields.
func parsedQueryToStruct(pqs *ParsedQueryString, target any) error {
var field reflect.Value
targetFieldValues := target.(reflect.Value)
// Locate the top-level field in the struct.
field, err := findField(targetFieldValues, pqs.Key)
if err != nil {
return err
}
var mapKey string
if len(pqs.InnerKeys) != 0 {
// Traverse the nested struct fields to find the target element.
for _, p := range pqs.InnerKeys {
mapKey = p
field, err = findField(field, p)
if err != nil {
return err
}
}
}
// Validate that the target field can be set.
if !field.IsValid() || !field.CanSet() {
return fmt.Errorf("cannot set value to the attribute %s", field.String())
}
if field.Kind() == reflect.Struct {
return fmt.Errorf("cannot set value to the struct attribute %s", field.String())
} else if field.Kind() == reflect.Slice {
field.Set(reflect.ValueOf(splitValues(pqs.Values[0])))
} else if field.Kind() == reflect.Int || field.Kind() == reflect.Int8 || field.Kind() == reflect.Int16 ||
field.Kind() == reflect.Int32 || field.Kind() == reflect.Int64 {
i, err := strconv.ParseInt(strings.Join(pqs.Values, ","), 10, 64)
if err != nil {
return fmt.Errorf("cannot parse int for the attribute %s", field.String())
}
field.SetInt(i)
} else if field.Kind() == reflect.Uint || field.Kind() == reflect.Uint8 ||
field.Kind() == reflect.Uint16 || field.Kind() == reflect.Uint32 || field.Kind() == reflect.Uint64 {
ui, err := strconv.ParseUint(strings.Join(pqs.Values, ","), 10, 64)
if err != nil {
return fmt.Errorf("cannot parse int for the attribute %s", field.String())
}
field.SetUint(ui)
} else if field.Kind() == reflect.Float64 || field.Kind() == reflect.Float32 {
f, _ := strconv.ParseFloat(strings.Join(pqs.Values, ","), 64)
field.SetFloat(f)
} else if field.Kind() == reflect.Ptr && field.Type().Elem().Kind() == reflect.Int {
// Handle pointers to integers.
i, err := strconv.ParseInt(strings.Join(pqs.Values, ","), 10, 64)
if err != nil {
return fmt.Errorf("cannot parse int for the attribute %s", field.String())
}
// Allocate memory for the pointer if nil.
if field.IsNil() {
field.Set(reflect.New(field.Type().Elem()))
}
// Set the value of the integer.
field.Elem().SetInt(i)
} else if field.Kind() == reflect.Map {
// Ensure the map is initialized before setting values.
if field.IsNil() {
field.Set(reflect.MakeMap(field.Type()))
}
field.SetMapIndex(reflect.ValueOf(mapKey), reflect.ValueOf(strings.Join(pqs.Values, ",")))
} else {
field.SetString(strings.Join(pqs.Values, ","))
}
return nil
}
// splitValues splits a comma-separated string into a slice of strings.
func splitValues(input string) []string {
input = strings.TrimSpace(input)
// Handle special cases where the input is empty or just a comma.
if input == "" || input == "," {
return nil
}
separatedValues := strings.Split(input, ",")
return separatedValues
}
// findField locates a struct field by its name or goReq tag value.
func findField(fieldValues reflect.Value, fieldName string) (reflect.Value, error) {
caser := cases.Title(language.English, cases.NoLower)
// Check the struct tags first; if no tag matches, fall back to the field name.
switch fieldValues.Kind() {
case reflect.Struct:
for i := 0; i < fieldValues.NumField(); i++ {
f := fieldValues.Type().Field(i)
// Check if the tag matches.
tagValue := f.Tag.Get(GoReqTag)
if tagValue == fieldName {
return fieldValues.Field(i), nil
}
// Check if the field name matches.
if f.Name == caser.String(fieldName) {
return fieldValues.Field(i), nil
}
}
case reflect.Map:
// Ensure the map keys are strings.
if fieldValues.Type().Key().Kind() != reflect.String {
return reflect.Value{}, fmt.Errorf("map keys must be strings, found %s",
fieldValues.Type().Key().Kind())
}
return fieldValues, nil
default:
return reflect.Value{}, fmt.Errorf("unsupported type: %s", fieldValues.Kind())
}
return reflect.Value{}, fmt.Errorf("field %q not found", fieldName)
}