-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcrud_ctrl_forms.go
More file actions
89 lines (84 loc) · 2.31 KB
/
crud_ctrl_forms.go
File metadata and controls
89 lines (84 loc) · 2.31 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
package crudex
import (
"fmt"
"net/http"
"reflect"
"strconv"
"github.com/gin-gonic/gin"
)
func BindForm[T any](r *http.Request, out *T) error {
// Parse the form data from the request.
if err := r.ParseForm(); err != nil {
return err
}
// Reflect on the struct to set values.
val := reflect.ValueOf(out).Elem()
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
// Get form value for the field name.
formValue := r.FormValue(fieldType.Name)
// Check if the field can be set and if the form value is not empty.
if field.CanSet() && formValue != "" {
// Convert form values to the appropriate field types.
// This example assumes all fields are strings for simplicity.
// You might need to convert this based on the field type.
field.SetString(formValue)
}
}
return nil
}
// DefaultFormHandler is a default form binder that binds the form data to a model using the form field names as the model field names
func DefaultFormHandler[T IModel](c *gin.Context, out *T) error {
if err := c.Request.ParseForm(); err != nil {
return err
}
val := reflect.ValueOf(out).Elem()
typ := val.Type()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
fieldType := typ.Field(i)
formValue := c.PostForm(fieldType.Name)
// we only set the field if we are able to do so and the form value is not empty
if field.CanSet() && formValue != "" {
switch fieldType.Type.Kind() {
case reflect.Uint:
val, err := strconv.ParseUint(formValue, 10, 64)
if err != nil {
return err
}
field.SetUint(val)
case reflect.String:
field.SetString(formValue)
case reflect.Int:
val, err := strconv.ParseInt(formValue, 10, 64)
if err != nil {
return err
}
field.SetInt(val)
case reflect.Float32:
val, err := strconv.ParseFloat(formValue, 32)
if err != nil {
return err
}
field.SetFloat(val)
case reflect.Float64:
val, err := strconv.ParseFloat(formValue, 64)
if err != nil {
return err
}
field.SetFloat(val)
case reflect.Bool:
if formValue == "true" || formValue == "checked" || formValue == "1" {
field.SetBool(true)
} else {
field.SetBool(false)
}
default:
return fmt.Errorf("Unsupported type: %s", fieldType.Type.Kind())
}
}
}
return nil
}