-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
196 lines (168 loc) · 5.27 KB
/
types.go
File metadata and controls
196 lines (168 loc) · 5.27 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
// Package callingcode provides a Go client for the Country Calling Code API.
//
// For more information, visit: https://apiverve.com/marketplace/callingcode?utm_source=go&utm_medium=readme
package callingcode
import (
"fmt"
"reflect"
"regexp"
"strings"
)
// ValidationRule defines validation constraints for a parameter.
type ValidationRule struct {
Type string
Required bool
Min *float64
Max *float64
MinLength *int
MaxLength *int
Format string
Enum []string
}
// ValidationError represents a parameter validation error.
type ValidationError struct {
Errors []string
}
func (e *ValidationError) Error() string {
return "Validation failed: " + strings.Join(e.Errors, "; ")
}
// Helper functions for pointers
func float64Ptr(v float64) *float64 { return &v }
func intPtr(v int) *int { return &v }
// Format validation patterns
var formatPatterns = map[string]*regexp.Regexp{
"email": regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`),
"url": regexp.MustCompile(`^https?://.+`),
"ip": regexp.MustCompile(`^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$`),
"date": regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`),
"hexColor": regexp.MustCompile(`^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$`),
}
// Request contains the parameters for the Country Calling Code API.
//
// Parameters:
// - country (required): string - The 2 letter ISO code for the country (e.g. FR) [minLength: 2, maxLength: 2]
type Request struct {
Country string `json:"country"` // Required
}
// ToQueryParams converts the request struct to a map of query parameters.
// Only non-zero values are included.
func (r *Request) ToQueryParams() map[string]string {
params := make(map[string]string)
if r == nil {
return params
}
v := reflect.ValueOf(*r)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldType := t.Field(i)
// Get the json tag for the field name
jsonTag := fieldType.Tag.Get("json")
if jsonTag == "" {
continue
}
// Handle tags like `json:"name,omitempty"`
jsonName := strings.Split(jsonTag, ",")[0]
if jsonName == "-" {
continue
}
// Skip zero values
if field.IsZero() {
continue
}
// Convert to string
params[jsonName] = fmt.Sprintf("%v", field.Interface())
}
return params
}
// Validate checks the request parameters against validation rules.
// Returns a ValidationError if validation fails, nil otherwise.
func (r *Request) Validate() error {
rules := map[string]ValidationRule{
"country": {Type: "string", Required: true, MinLength: intPtr(2), MaxLength: intPtr(2)},
}
if len(rules) == 0 {
return nil
}
var errors []string
v := reflect.ValueOf(*r)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
fieldType := t.Field(i)
jsonTag := fieldType.Tag.Get("json")
if jsonTag == "" {
continue
}
jsonName := strings.Split(jsonTag, ",")[0]
rule, exists := rules[jsonName]
if !exists {
continue
}
// Check required
if rule.Required && field.IsZero() {
errors = append(errors, fmt.Sprintf("Required parameter [%s] is missing", jsonName))
continue
}
if field.IsZero() {
continue
}
// Type-specific validation
switch rule.Type {
case "integer", "number":
var numVal float64
switch field.Kind() {
case reflect.Int, reflect.Int64:
numVal = float64(field.Int())
case reflect.Float64:
numVal = field.Float()
}
if rule.Min != nil && numVal < *rule.Min {
errors = append(errors, fmt.Sprintf("Parameter [%s] must be at least %v", jsonName, *rule.Min))
}
if rule.Max != nil && numVal > *rule.Max {
errors = append(errors, fmt.Sprintf("Parameter [%s] must be at most %v", jsonName, *rule.Max))
}
case "string":
strVal := field.String()
if rule.MinLength != nil && len(strVal) < *rule.MinLength {
errors = append(errors, fmt.Sprintf("Parameter [%s] must be at least %d characters", jsonName, *rule.MinLength))
}
if rule.MaxLength != nil && len(strVal) > *rule.MaxLength {
errors = append(errors, fmt.Sprintf("Parameter [%s] must be at most %d characters", jsonName, *rule.MaxLength))
}
if rule.Format != "" {
if pattern, ok := formatPatterns[rule.Format]; ok {
if !pattern.MatchString(strVal) {
errors = append(errors, fmt.Sprintf("Parameter [%s] must be a valid %s", jsonName, rule.Format))
}
}
}
}
// Enum validation
if len(rule.Enum) > 0 {
strVal := fmt.Sprintf("%v", field.Interface())
found := false
for _, enumVal := range rule.Enum {
if strVal == enumVal {
found = true
break
}
}
if !found {
errors = append(errors, fmt.Sprintf("Parameter [%s] must be one of: %s", jsonName, strings.Join(rule.Enum, ", ")))
}
}
}
if len(errors) > 0 {
return &ValidationError{Errors: errors}
}
return nil
}
// ResponseData contains the data returned by the Country Calling Code API.
type ResponseData struct {
Country string `json:"country"`
OfficialName string `json:"officialName"`
CountryCode string `json:"countryCode"`
Callingcodes []string `json:"callingcodes"`
}