-
Notifications
You must be signed in to change notification settings - Fork 81
/
request.go
97 lines (88 loc) · 2.48 KB
/
request.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
// Copyright 2022 The kubegems.io Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package request
import (
"encoding/json"
"encoding/xml"
"net/http"
"strconv"
"strings"
)
type ListOptions struct {
Page int `json:"page,omitempty"`
Size int `json:"size,omitempty"`
Search string `json:"search,omitempty"`
Sort string `json:"sort,omitempty"`
Filter string `json:"filter,omitempty"`
}
// nolint: gomnd
func GetListOptions(r *http.Request) ListOptions {
return ListOptions{
Page: Query(r, "page", 1),
Size: Query(r, "size", 10),
Search: Query(r, "search", ""),
Sort: Query(r, "sort", ""),
}
}
func HeaderOrQuery[T any](r *http.Request, key string, defaultValue T) T {
if val := r.Header.Get(key); val == "" {
return ValueOrDefault(r.URL.Query().Get(key), defaultValue)
} else {
return ValueOrDefault(val, defaultValue)
}
}
func Header[T any](r *http.Request, key string, defaultValue T) T {
val := r.Header.Get(key)
return ValueOrDefault(val, defaultValue)
}
func Query[T any](r *http.Request, key string, defaultValue T) T {
val := r.URL.Query().Get(key)
return ValueOrDefault(val, defaultValue)
}
// nolint: forcetypeassert,gomnd,ifshort
// ValueOrDefault return default value if empty string
func ValueOrDefault[T any](val string, defaultValue T) T {
if val == "" {
return defaultValue
}
switch any(defaultValue).(type) {
case string:
return any(val).(T)
case []string:
if val == "" {
return defaultValue
}
return any(strings.Split(val, ",")).(T)
case int:
intval, _ := strconv.Atoi(val)
return any(intval).(T)
case bool:
b, _ := strconv.ParseBool(val)
return any(b).(T)
case int64:
intval, _ := strconv.ParseInt(val, 10, 64)
return any(intval).(T)
default:
return defaultValue
}
}
func Body(r *http.Request, into any) error {
switch r.Header.Get("Content-Type") {
case "application/json", "":
return json.NewDecoder(r.Body).Decode(into)
case "application/xml":
return xml.NewDecoder(r.Body).Decode(into)
}
return nil
}