-
Notifications
You must be signed in to change notification settings - Fork 0
/
req.go
55 lines (44 loc) · 1014 Bytes
/
req.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
package podutil
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/google/go-querystring/query"
)
type RequestOption func(*http.Request) error
func RequestMethod(m string) RequestOption {
return func(r *http.Request) error {
r.Method = m
return nil
}
}
func RequestJSONBody(data any) RequestOption {
return func(r *http.Request) error {
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(data)
if err != nil {
return fmt.Errorf("encode json body: %w", err)
}
r.Header.Set("Content-Type", "application/json")
r.Body = io.NopCloser(buf)
return nil
}
}
func RequestQueryStruct(data any) RequestOption {
return func(r *http.Request) error {
v, err := query.Values(data)
if err != nil {
return fmt.Errorf("pull image: %w", err)
}
r.URL.RawQuery = v.Encode()
return nil
}
}
func RequestPath(path string, a ...any) RequestOption {
return func(r *http.Request) error {
r.URL.Path = r.URL.Path + fmt.Sprintf(path, a...)
return nil
}
}