-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
140 lines (124 loc) · 3.24 KB
/
utils.go
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
package api
import (
"encoding/json"
"github.com/go-playground/validator"
"github.com/gorilla/schema"
"net/http"
"reflect"
"strconv"
"strings"
"time"
uuid "github.com/satori/go.uuid"
)
var (
validate = validator.New()
decodeSchema = (*schema.Decoder).Decode
parseFormRequest = (*http.Request).ParseForm
parseMultiPartFormRequest = (*http.Request).ParseMultipartForm
doHandleDecodeSchema = decodeSchemaRequest
)
const (
ContentURLEncoded string = "application/x-www-form-urlencoded"
ContentJSON string = "application/json"
ContentFormData string = "multipart/form-data"
ErrParsedBodyCode string = "ERROR_PARSING_BODY"
ErrDecodeBodyCode string = "ERROR_DECODE_BODY"
)
func WriteJson(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
b, _ := json.Marshal(data)
_, _ = w.Write(b)
}
type ValidationError struct {
Field string `json:"field"`
Tag string `json:"tag"`
Value string `json:"value"`
}
func ValidateStruct(data interface{}) []*ValidationError {
var errors []*ValidationError
err := validate.Struct(data)
if err != nil {
for _, err := range err.(validator.ValidationErrors) {
var element ValidationError
element.Field = err.StructNamespace()
element.Tag = err.Tag()
element.Value = err.Param()
errors = append(errors, &element)
}
}
return errors
}
func ArrContains[T string | int | float32](arr []T, val T) bool {
for _, a := range arr {
if a == val {
return true
}
}
return false
}
func GetStructKey(field reflect.StructField) string {
var key string
key = field.Tag.Get("db")
if key == "" {
key = field.Tag.Get("json")
}
if key == "" {
key = strings.ToLower(field.Name)
}
return key
}
func GetStructValue(value reflect.Value) interface{} {
intc := value.Interface()
switch intc.(type) {
case int, int8, int16, int32, int64:
return value.Int()
case float32, float64:
return value.Float()
case bool:
return value.Bool()
case time.Time:
return value.Interface().(time.Time).String()
case uuid.UUID:
return value.Interface().(uuid.UUID).String()
default:
return value.String()
}
}
func GenerateQueryComponenFromStruct(model interface{}, skips []string) (string, []interface{}, string) {
var fields []string
var values []interface{}
var binds []string
v := reflect.ValueOf(model)
for i := 0; i < v.NumField(); i++ {
key := GetStructKey(v.Type().Field(i))
value := GetStructValue(v.Field(i))
if ArrContains(skips, key) {
break
}
fields = append(fields, key)
values = append(values, value)
binds = append(binds, "$"+strconv.Itoa(len(values)))
}
return strings.Join(fields, ", "), values, strings.Join(binds, ", ")
}
// filterFlags is a utility to cleanly get a Content-Type header
// refer to https://github.com/gin-gonic/gin/blob/master/utils.go#L83
func filterFlags(content string) string {
for i, char := range content {
if char == ' ' || char == ';' {
return content[:i]
}
}
return content
}
func decodeSchemaRequest(r *http.Request, val interface{}) error {
decoder.IgnoreUnknownKeys(true)
sourceDecode := r.Form
if r.Method == http.MethodGet {
sourceDecode = r.URL.Query()
}
if err := decodeSchema(decoder, val, sourceDecode); err != nil {
return err
}
return nil
}