57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package testutil
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
)
|
|
|
|
// Option is a function type for configuring HTTP requests
|
|
type Option func(*http.Request)
|
|
|
|
// WithBody adds a request body
|
|
func WithBody(body string) Option {
|
|
return func(r *http.Request) {
|
|
r.Body = io.NopCloser(strings.NewReader(body))
|
|
}
|
|
}
|
|
|
|
// WithHeader adds a request header
|
|
func WithHeader(name, value string) Option {
|
|
return func(r *http.Request) {
|
|
r.Header.Set(name, value)
|
|
}
|
|
}
|
|
|
|
// WithAuthToken adds an Authorization Bearer token to the request
|
|
func WithAuthToken(token string) Option {
|
|
return func(r *http.Request) {
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
}
|
|
|
|
// NewTestRequest creates a new HTTP test request with the specified method, path, and options
|
|
func NewTestRequest(method, path string, opts ...Option) *http.Request {
|
|
r := httptest.NewRequest(method, path, nil)
|
|
for _, opt := range opts {
|
|
opt(r)
|
|
}
|
|
return r
|
|
}
|
|
|
|
// PerformRequest executes a request against a handler and returns the response recorder
|
|
func PerformRequest(handler http.HandlerFunc, method, path string, opts ...Option) *httptest.ResponseRecorder {
|
|
w := httptest.NewRecorder()
|
|
r := NewTestRequest(method, path, opts...)
|
|
handler(w, r)
|
|
return w
|
|
}
|
|
|
|
// PerformRequestWithHandler executes a request against an http.Handler and returns the response recorder
|
|
func PerformRequestWithHandler(handler http.Handler, method, path string, opts ...Option) *httptest.ResponseRecorder {
|
|
w := httptest.NewRecorder()
|
|
r := NewTestRequest(method, path, opts...)
|
|
handler.ServeHTTP(w, r)
|
|
return w
|
|
}
|