forked from OpenAPITools/openapi-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouters.go
More file actions
373 lines (305 loc) · 8.29 KB
/
routers.go
File metadata and controls
373 lines (305 loc) · 8.29 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
362
363
364
365
366
367
368
369
370
371
372
373
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
/*
* OpenAPI Petstore
*
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* API version: 1.0.0
*/
package petstoreserver
import (
"encoding/json"
"errors"
"time"
"github.com/gorilla/mux"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
)
// A Route defines the parameters for an api endpoint
type Route struct {
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
// Routes is a map of defined api endpoints
type Routes map[string]Route
// Router defines the required methods for retrieving api routes
type Router interface {
Routes() Routes
}
const errMsgRequiredMissing = "required parameter is missing"
const errMsgMinValueConstraint = "provided parameter is not respecting minimum value constraint"
const errMsgMaxValueConstraint = "provided parameter is not respecting maximum value constraint"
// NewRouter creates a new router for any number of api routers
func NewRouter(routers ...Router) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, api := range routers {
for name, route := range api.Routes() {
var handler http.Handler = route.HandlerFunc
handler = Logger(handler, name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(name).
Handler(handler)
}
}
return router
}
// EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code
func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, w http.ResponseWriter) error {
wHeader := w.Header()
for key, values := range headers {
for _, value := range values {
wHeader.Add(key, value)
}
}
f, ok := i.(*os.File)
if ok {
data, err := io.ReadAll(f)
if err != nil {
return err
}
wHeader.Set("Content-Type", http.DetectContentType(data))
wHeader.Set("Content-Disposition", "attachment; filename="+filepath.Base(f.Name()))
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
_, err = w.Write(data)
return err
}
wHeader.Set("Content-Type", "application/json; charset=UTF-8")
if status != nil {
w.WriteHeader(*status)
} else {
w.WriteHeader(http.StatusOK)
}
if i != nil {
return json.NewEncoder(w).Encode(i)
}
return nil
}
// ReadFormFileToTempFile reads file data from a request form and writes it to a temporary file
func ReadFormFileToTempFile(r *http.Request, key string) (*os.File, error) {
_, fileHeader, err := r.FormFile(key)
if err != nil {
return nil, err
}
return readFileHeaderToTempFile(fileHeader)
}
// ReadFormFilesToTempFiles reads files array data from a request form and writes it to a temporary files
func ReadFormFilesToTempFiles(r *http.Request, key string) ([]*os.File, error) {
if err := r.ParseMultipartForm(32 << 20); err != nil {
return nil, err
}
files := make([]*os.File, 0, len(r.MultipartForm.File[key]))
for _, fileHeader := range r.MultipartForm.File[key] {
file, err := readFileHeaderToTempFile(fileHeader)
if err != nil {
return nil, err
}
files = append(files, file)
}
return files, nil
}
// readFileHeaderToTempFile reads multipart.FileHeader and writes it to a temporary file
func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error) {
formFile, err := fileHeader.Open()
if err != nil {
return nil, err
}
defer formFile.Close()
// Use .* as suffix, because the asterisk is a placeholder for the random value,
// and the period allows consumers of this file to remove the suffix to obtain the original file name
file, err := os.CreateTemp("", fileHeader.Filename+".*")
if err != nil {
return nil, err
}
defer file.Close()
_, err = io.Copy(file, formFile)
if err != nil {
return nil, err
}
return file, nil
}
func parseTimes(param string) ([]time.Time, error) {
splits := strings.Split(param, ",")
times := make([]time.Time, 0, len(splits))
for _, v := range splits {
t, err := parseTime(v)
if err != nil {
return nil, err
}
times = append(times, *t)
}
return times, nil
}
// parseTime will parses a string parameter into a time.Time using the RFC3339 format
func parseTime(param string) (*time.Time, error) {
if param == "" {
return nil, nil
}
v, err := time.Parse(time.RFC3339, param)
return &v, err
}
type Number interface {
~int32 | ~int64 | ~float32 | ~float64
}
type ParseString[T Number | string | bool] func(v string) (*T, error)
// parseFloat64 parses a string parameter to an float64.
func parseFloat64(param string) (*float64, error) {
if param == "" {
return nil, nil
}
v, err := strconv.ParseFloat(param, 64)
return &v, err
}
// parseFloat32 parses a string parameter to an float32.
func parseFloat32(param string) (*float32, error) {
if param == "" {
return nil, nil
}
v, err := strconv.ParseFloat(param, 32)
f := float32(v)
return &f, err
}
// parseInt64 parses a string parameter to an int64.
func parseInt64(param string) (*int64, error) {
if param == "" {
return nil, nil
}
v, err := strconv.ParseInt(param, 10, 64)
return &v, err
}
// parseInt32 parses a string parameter to an int32.
func parseInt32(param string) (*int32, error) {
if param == "" {
return nil, nil
}
val, err := strconv.ParseInt(param, 10, 32)
v := int32(val)
return &v, err
}
// parseBool parses a string parameter to an bool.
func parseBool(param string) (*bool, error) {
if param == "" {
return nil, nil
}
b, err := strconv.ParseBool(param)
return &b, err
}
type Operation[T Number | string | bool] func(actual string) (*T, bool, error)
func WithRequire[T Number | string | bool](parse ParseString[T]) Operation[T] {
return func(actual string) (*T, bool, error) {
if actual == "" {
return nil, false, errors.New(errMsgRequiredMissing)
}
v, err := parse(actual)
return v, false, err
}
}
func WithDefaultOrParse[T Number | string | bool](def T, parse ParseString[T]) Operation[T] {
return func(actual string) (*T, bool, error) {
if actual == "" {
return &def, true, nil
}
v, err := parse(actual)
return v, false, err
}
}
func WithParse[T Number | string | bool](parse ParseString[T]) Operation[T] {
return func(actual string) (*T, bool, error) {
v, err := parse(actual)
return v, false, err
}
}
type Constraint[T Number | string | bool] func(actual T) error
func WithMinimum[T Number](expected T) Constraint[T] {
return func(actual T) error {
if actual < expected {
return errors.New(errMsgMinValueConstraint)
}
return nil
}
}
func WithMaximum[T Number](expected T) Constraint[T] {
return func(actual T) error {
if actual > expected {
return errors.New(errMsgMaxValueConstraint)
}
return nil
}
}
// parseNumericParameter parses a numeric parameter to its respective type.
func parseNumericParameter[T Number](param string, fn Operation[T], checks ...Constraint[T]) (*T, error) {
v, ok, err := fn(param)
if err != nil {
return nil, err
}
if v == nil {
return nil, nil
}
if !ok {
for _, check := range checks {
if err := check(*v); err != nil {
return nil, err
}
}
}
return v, nil
}
// parseBoolParameter parses a string parameter to a bool
func parseBoolParameter(param string, fn Operation[bool]) (*bool, error) {
if param == "" {
return nil, nil
}
v, _, err := fn(param)
return v, err
}
// parseNumericArrayParameter parses a string parameter containing array of values to its respective type.
func parseNumericArrayParameter[T Number](param, delim string, required bool, fn Operation[T], checks ...Constraint[T]) ([]T, error) {
if param == "" {
if required {
return nil, errors.New(errMsgRequiredMissing)
}
return nil, nil
}
str := strings.Split(param, delim)
values := make([]T, len(str))
for i, s := range str {
v, ok, err := fn(s)
if err != nil {
return nil, err
}
if !ok {
for _, check := range checks {
if err := check(*v); err != nil {
return nil, err
}
}
}
values[i] = *v
}
return values, nil
}
// parseQuery parses query parameters and returns an error if any malformed value pairs are encountered.
func parseQuery(rawQuery string) (url.Values, error) {
return url.ParseQuery(rawQuery)
}
func getPointerOrNilIfEmpty(v string) *string {
if v == "" {
return nil
}
return &v
}
func getPointer[T any](v T) *T {
return &v
}