summaryrefslogtreecommitdiff
path: root/pkg/test/http.go
blob: b65ccc94c143f1f6835d3c3afd88a8715b165466 (plain)
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
package test

import (
	"bytes"
	"context"
	"io"
	"net/http"
	"net/http/httptest"

	xcontext "github.com/xlgmokha/x/pkg/context"
	"github.com/xlgmokha/x/pkg/serde"
	"github.com/xlgmokha/x/pkg/x"
)

type RequestOption x.Option[*http.Request]

func Request(method, target string, options ...RequestOption) *http.Request {
	request := httptest.NewRequest(method, target, nil)
	for _, option := range options {
		request = option(request)
	}
	return request
}

func RequestResponse(method, target string, options ...RequestOption) (*http.Request, *httptest.ResponseRecorder) {
	return Request(method, target, options...), httptest.NewRecorder()
}

func WithAcceptHeader(value serde.MediaType) RequestOption {
	return WithRequestHeader("Accept", string(value))
}

func WithRequestHeader(key, value string) RequestOption {
	return func(r *http.Request) *http.Request {
		r.Header.Set(key, value)
		return r
	}
}

func WithContentType[T any](item T, mediaType serde.MediaType) RequestOption {
	body := bytes.NewBuffer(nil)
	x.Check(serde.To[T](body, item, mediaType))
	return WithRequestBody(io.NopCloser(body))
}

func WithRequestBody(body io.ReadCloser) RequestOption {
	return func(r *http.Request) *http.Request {
		r.Body = body
		return r
	}
}

func WithContext(ctx context.Context) RequestOption {
	return func(r *http.Request) *http.Request {
		return r.WithContext(ctx)
	}
}

func WithContextKeyValue[T any](ctx context.Context, key xcontext.Key[T], item T) RequestOption {
	return WithContext(key.With(ctx, item))
}

func WithCookie(cookie *http.Cookie) RequestOption {
	return func(r *http.Request) *http.Request {
		r.AddCookie(cookie)
		return r
	}
}