main
1package test
2
3import (
4 "bytes"
5 "context"
6 "io"
7 "net/http"
8 "net/http/httptest"
9
10 "github.com/xlgmokha/x/pkg/serde"
11 "github.com/xlgmokha/x/pkg/x"
12)
13
14type RequestOption func(*http.Request) *http.Request
15
16func Request(method, target string, options ...RequestOption) *http.Request {
17 request := httptest.NewRequest(method, target, nil)
18 for _, option := range options {
19 request = option(request)
20 }
21 return request
22}
23
24func RequestResponse(method, target string, options ...RequestOption) (*http.Request, *httptest.ResponseRecorder) {
25 return Request(method, target, options...), httptest.NewRecorder()
26}
27
28func WithAcceptHeader(value serde.MediaType) RequestOption {
29 return WithRequestHeader("Accept", string(value))
30}
31
32func WithRequestHeader(key, value string) RequestOption {
33 return func(r *http.Request) *http.Request {
34 r.Header.Set(key, value)
35 return r
36 }
37}
38
39func WithContentType[T any](item T, mediaType serde.MediaType) RequestOption {
40 body := bytes.NewBuffer(nil)
41 x.Check(serde.To[T](body, item, mediaType))
42 return WithRequestBody(io.NopCloser(body))
43}
44
45func WithRequestBody(body io.ReadCloser) RequestOption {
46 return func(r *http.Request) *http.Request {
47 r.Body = body
48 return r
49 }
50}
51
52func WithContext(ctx context.Context) RequestOption {
53 return func(r *http.Request) *http.Request {
54 return r.WithContext(ctx)
55 }
56}
57
58func WithCookie(cookie *http.Cookie) RequestOption {
59 return func(r *http.Request) *http.Request {
60 r.AddCookie(cookie)
61 return r
62 }
63}