-
Notifications
You must be signed in to change notification settings - Fork 1
/
requestoptions.go
64 lines (56 loc) · 1.63 KB
/
requestoptions.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
// Copyright (c) 2024 0x9ef. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package clientx
import (
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/gorilla/schema"
)
type RequestOption func(req *http.Request) error
// WithRequestQueryParams encodes query params automatically by accesing fields with custom tag.
func WithRequestQueryParams[T any](tag string, params ...T) RequestOption {
return func(req *http.Request) error {
q := req.URL.Query()
enc := schema.NewEncoder()
enc.SetAliasTag(tag)
for _, param := range params {
if err := enc.Encode(param, q); err != nil {
return fmt.Errorf("failed to encode query params: %w", err)
}
}
req.URL.RawQuery = q.Encode()
return nil
}
}
// WithRequestQueryEncodableParams encodes query params by implementing ParamEncoder[T] interface,
// calls Encode(url.Values) functional to set query params.
func WithRequestQueryEncodableParams[T any](params ...ParamEncoder[T]) RequestOption {
return func(req *http.Request) error {
q := req.URL.Query()
for _, param := range params {
if err := param.Encode(q); err != nil {
return fmt.Errorf("failed to encode query params: %w", err)
}
}
req.URL.RawQuery = q.Encode()
return nil
}
}
func WithRequestForm(form url.Values) RequestOption {
return func(req *http.Request) error {
req.Body = io.NopCloser(strings.NewReader(form.Encode()))
return nil
}
}
func WithRequestHeaders(headers map[string][]string) RequestOption {
return func(req *http.Request) error {
for key, val := range headers {
req.Header[key] = val
}
return nil
}
}