-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp2struct.go
More file actions
361 lines (277 loc) · 8.41 KB
/
http2struct.go
File metadata and controls
361 lines (277 loc) · 8.41 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
// Package http2struct provides functionality to automatically map HTTP request data
// into Go struct fields using struct tags.
//
// It supports mapping from various sources:
// - JSON request body
// - Form fields
// - URL query parameters
// - Path parameters
// - HTTP headers
// - File uploads (both multipart and binary)
package http2struct
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"reflect"
"strconv"
"strings"
)
// File represents an uploaded file from an HTTP request
type File struct {
Name string // Original filename provided by the client
Size int64 // Size of the file in bytes
Content []byte // Raw content of the file
}
// Convert maps data from an HTTP request into a struct.
// The destination must be a pointer to a struct with appropriate tags.
//
// Supported struct tags:
// - `json:"field_name"` - Maps JSON body fields
// - `form:"field_name"` - Maps form fields
// - `query:"param_name"` - Maps URL query parameters
// - `path:"param_name"` - Maps URL path parameters
// - `header:"Header-Name"` - Maps HTTP headers
// - `file:"field_name"` - Maps uploaded files from multipart forms
// - `file:"binary"` - Maps the entire request body as a file
func Convert(request *http.Request, destination any) error {
if request == nil {
return fmt.Errorf("request cannot be nil")
}
destinationType := reflect.TypeOf(destination)
if destinationType == nil {
return fmt.Errorf("destination cannot be nil")
}
if destinationType.Kind() != reflect.Ptr {
return fmt.Errorf("destination must be a pointer")
}
destinationType = destinationType.Elem()
if destinationType.Kind() != reflect.Struct {
return fmt.Errorf("destination must be a struct")
}
if err := convertBody(request, destination, destinationType); err != nil {
return fmt.Errorf("failed to convert body: %w", err)
}
v := reflect.ValueOf(destination).Elem()
for i := range destinationType.NumField() {
field := destinationType.Field(i)
if !field.IsExported() {
continue
}
fieldValue := v.Field(i)
if !fieldValue.CanSet() {
continue
}
tag, ok := field.Tag.Lookup("form")
if ok && tag != "" && tag != "-" {
fieldValue.SetZero()
if request.PostForm == nil {
if err := request.ParseMultipartForm(32 << 20); err != nil {
return fmt.Errorf("failed to parse request multipart form: %w", err)
}
}
var v string
if p := request.PostForm[tag]; len(p) > 0 {
v = p[0]
}
if err := convert(fieldValue, field.Type, v); err != nil {
return fmt.Errorf("failed to convert %q form to %q field: %w", tag, field.Name, err)
}
continue
}
tag, ok = field.Tag.Lookup("file")
if ok && tag != "" && tag != "-" && tag != "binary" {
fieldValue.SetZero()
if field.Type.Kind() != reflect.Pointer && field.Type != reflect.TypeOf(File{}) {
return fmt.Errorf("%q type is not supported for %q field", fieldValue.Type().String(), field.Name)
}
if field.Type.Kind() == reflect.Pointer && field.Type != reflect.TypeOf(&File{}) {
return fmt.Errorf("%q type is not supported for %q field", fieldValue.Type().String(), field.Name)
}
base, _, _ := strings.Cut(request.Header.Get("Content-Type"), ";")
if strings.TrimSpace(base) != "multipart/form-data" {
continue
}
file, fileHeader, err := request.FormFile(tag)
if errors.Is(err, http.ErrMissingFile) {
continue
}
if err != nil {
return fmt.Errorf("failed to get %q form file for %q field: %w", tag, field.Name, err)
}
defer file.Close()
content, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("failed to read %q form file content for %q field: %w", tag, field.Name, err)
}
f := File{
Name: fileHeader.Filename,
Size: fileHeader.Size,
Content: content,
}
if field.Type.Kind() == reflect.Pointer {
fieldValue.Set(reflect.ValueOf(&f))
continue
}
fieldValue.Set(reflect.ValueOf(f))
continue
}
tag, ok = field.Tag.Lookup("file")
if ok && tag == "binary" {
fieldValue.SetZero()
if field.Type.Kind() != reflect.Pointer && field.Type != reflect.TypeOf(File{}) {
return fmt.Errorf("%q type is not supported for %q field", fieldValue.Type().String(), field.Name)
}
if field.Type.Kind() == reflect.Pointer && field.Type != reflect.TypeOf(&File{}) {
return fmt.Errorf("%q type is not supported for %q field", fieldValue.Type().String(), field.Name)
}
if request.ContentLength == 0 {
return nil
}
contentDisposition := request.Header.Get("Content-Disposition")
_, params, err := mime.ParseMediaType(contentDisposition)
if err != nil {
continue
}
filename := params["filename"]
if filename == "" {
filename = params["filename*"]
}
if filename == "" {
continue
}
content, err := io.ReadAll(request.Body)
if err != nil {
return fmt.Errorf("failed to read %q raw body for %q field: %w", tag, field.Name, err)
}
f := File{
Name: filename,
Size: request.ContentLength,
Content: content,
}
if field.Type.Kind() == reflect.Pointer {
fieldValue.Set(reflect.ValueOf(&f))
continue
}
fieldValue.Set(reflect.ValueOf(f))
continue
}
tag, ok = field.Tag.Lookup("header")
if ok && tag != "" && tag != "-" {
fieldValue.SetZero()
v := request.Header.Get(tag)
if err := convert(fieldValue, field.Type, v); err != nil {
return fmt.Errorf("failed to convert %q header to %q field: %w", tag, field.Name, err)
}
continue
}
tag, ok = field.Tag.Lookup("query")
if ok && tag != "" && tag != "-" {
fieldValue.SetZero()
v := request.URL.Query().Get(tag)
if err := convert(fieldValue, field.Type, v); err != nil {
return fmt.Errorf("failed to convert %q query to %q field: %w", tag, field.Name, err)
}
continue
}
tag, ok = field.Tag.Lookup("path")
if ok && tag != "" && tag != "-" {
fieldValue.SetZero()
v := request.PathValue(tag)
if err := convert(fieldValue, field.Type, v); err != nil {
return fmt.Errorf("failed to convert %q path to %q field: %w", tag, field.Name, err)
}
continue
}
}
return nil
}
func convertBody(request *http.Request, destination any, destinationType reflect.Type) error {
if request.ContentLength == 0 {
return nil
}
base, _, _ := strings.Cut(request.Header.Get("Content-Type"), ";")
if strings.TrimSpace(base) != "application/json" {
return nil
}
for i := range destinationType.NumField() {
field := destinationType.Field(i)
if !field.IsExported() {
continue
}
tag, ok := field.Tag.Lookup("json")
if !ok {
continue
}
if tag == "-" {
continue
}
if err := json.NewDecoder(request.Body).Decode(destination); err != nil {
return fmt.Errorf("failed to decode request body: %w", err)
}
break
}
return nil
}
func convert(field reflect.Value, fieldType reflect.Type, value string) error {
if value == "" {
return nil
}
var err error
switch field.Kind() {
case reflect.Bool:
var v bool
v, err = strconv.ParseBool(value)
if err == nil {
field.SetBool(v)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var v int64
v, err = strconv.ParseInt(value, 10, fieldType.Bits())
if err == nil {
field.SetInt(v)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
var v uint64
v, err = strconv.ParseUint(value, 10, fieldType.Bits())
if err == nil {
field.SetUint(v)
}
case reflect.Float32, reflect.Float64:
var v float64
v, err = strconv.ParseFloat(value, fieldType.Bits())
if err == nil {
field.SetFloat(v)
}
case reflect.Complex64, reflect.Complex128:
var v complex128
v, err = strconv.ParseComplex(value, fieldType.Bits())
if err == nil {
field.SetComplex(v)
}
case reflect.Slice:
element := fieldType.Elem()
if element.Kind() == reflect.Slice {
return fmt.Errorf("slice element kind %q is not supported", element.Kind().String())
}
parts := strings.Split(value, ",")
slice := reflect.MakeSlice(fieldType, len(parts), len(parts))
for i, part := range parts {
if err := convert(slice.Index(i), element, part); err != nil {
return fmt.Errorf("failed to convert slice element for index %d: %w", i, err)
}
}
field.Set(slice)
case reflect.String:
field.SetString(value)
default:
return fmt.Errorf("kind %q is not supported", field.Kind().String())
}
if err != nil {
return fmt.Errorf("failed to parse value to %q: %w", field.Kind().String(), err)
}
return nil
}