request

package
v1.26.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 26, 2024 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package request provides to define immutable HTTP requests, see NewHTTPRequest function.

Requests are sent using the Sender interface. The client.Client is a default implementation of the request.Sender interface based on the standard net/http package.

APIRequest[R Result] is a generic type that wraps one or more HTTPRequest. It contains target data type to which the API response will be mapped. Use NewAPIRequest function to create a APIRequest from a HTTPRequest.

RunGroup, WaitGroup, ParallelAPIRequests are helpers for concurrent requests.

Index

Constants

View Source
const (
	APIRequestSpanName = "keboola.go.api.client.request"
)
View Source
const RunGroupConcurrencyLimit = 32

RunGroupConcurrencyLimit is the maximum number of concurrent requests in one RunGroup.

View Source
const WaitGroupConcurrencyLimit = 8

WaitGroupConcurrencyLimit is the maximum number of concurrent requests in one WaitGroup.

Variables

This section is empty.

Functions

func StructToMap

func StructToMap(in any, allowedFields []string) (out map[string]any)

StructToMap converts a struct to values map. Only defined allowedFields are converted. If allowedFields = nil, then all fields are exported.

Field name is read from `writeas` tag or from "json" tag as fallback. Field with tag `readonly:"true"` is ignored. Field with tag `writeoptional` is exported only if value is not empty.

func ToFormBody

func ToFormBody(in map[string]any) (out map[string]string)

ToFormBody converts a JSON like map to form body map, any type is mapped to string.

Types

type APIRequest

type APIRequest[R Result] interface {
	// WithBefore method registers callback to be executed before the request.
	// If an error is returned, the request is not sent.
	WithBefore(func(ctx context.Context) error) APIRequest[R]
	// WithOnComplete method registers callback to be executed when the request is completed.
	WithOnComplete(func(ctx context.Context, result R, err error) error) APIRequest[R]
	// WithOnSuccess method registers callback to be executed when the request is completed and `code >= 200 and <= 299`.
	WithOnSuccess(func(ctx context.Context, result R) error) APIRequest[R]
	// WithOnError method registers callback to be executed when the request is completed and `code >= 400`.
	WithOnError(func(ctx context.Context, err error) error) APIRequest[R]
	// Send sends the request by the sender.
	Send(ctx context.Context) (result R, err error)
	SendOrErr(ctx context.Context) error
}

APIRequest with response mapped to the generic type R.

func NewAPIRequest

func NewAPIRequest[R Result](result R, requests ...Sendable) APIRequest[R]

NewAPIRequest creates an API request with the result mapped to the R type. It is composed of one or multiple Sendable (HTTPRequest or APIRequest).

func NewNoOperationAPIRequest

func NewNoOperationAPIRequest[R Result](result R) APIRequest[R]

NewNoOperationAPIRequest returns an APIRequest that immediately returns a Result without calling any HTTPRequest. It is handy in situations where there is no work to be done.

type HTTPRequest

type HTTPRequest interface {

	// WithHead is shortcut for WithMethod(http.MethodHead).WithURL(url)
	WithHead(url string) HTTPRequest
	// WithGet is shortcut for WithMethod(http.MethodGet).WithURL(url)
	WithGet(url string) HTTPRequest
	// WithPost is shortcut for WithMethod(http.MethodPost).WithURL(url)
	WithPost(url string) HTTPRequest
	// WithPatch is shortcut for WithMethod(http.MethodPatch).WithURL(url)
	WithPatch(url string) HTTPRequest
	// WithPut is shortcut for WithMethod(http.MethodPut).WithURL(url)
	WithPut(url string) HTTPRequest
	// WithDelete is shortcut for WithMethod(http.MethodDelete).WithURL(url)
	WithDelete(url string) HTTPRequest
	// WithMethod method sets the HTTP method.
	WithMethod(method string) HTTPRequest
	// WithBaseURL method sets the base URL.
	WithBaseURL(baseURL string) HTTPRequest
	// WithURL method sets the URL.
	WithURL(url string) HTTPRequest
	// WithURLValue method sets the URL.
	WithURLValue(url *url.URL) HTTPRequest
	// AndHeader method sets a single header field and its value.
	AndHeader(header string, value string) HTTPRequest
	// AndQueryParam method sets single parameter and its value.
	AndQueryParam(param, value string) HTTPRequest
	// WithQueryParams method sets multiple parameters and its values.
	WithQueryParams(params map[string]string) HTTPRequest
	// AndPathParam method sets single URL path key-value pair.
	AndPathParam(param, value string) HTTPRequest
	// WithPathParams method sets multiple URL path key-value pairs.
	WithPathParams(params map[string]string) HTTPRequest
	// WithFormBody method sets Form parameters and Content-Type header to "application/x-www-form-urlencoded".
	WithFormBody(form map[string]string) HTTPRequest
	// WithJSONBody method sets request body to the JSON value and Content-Type header to "application/json".
	WithJSONBody(body any) HTTPRequest
	// WithBody method sets request body.
	WithBody(body any) HTTPRequest
	// WithContentType method sets custom content type.
	WithContentType(contentType string) HTTPRequest
	// WithError method registers the request `Error` value for automatic mapping.
	WithError(err error) HTTPRequest
	// WithResult method registers the request `Result` value for automatic mapping.
	WithResult(result any) HTTPRequest
	// WithOnComplete method registers callback to be executed when the request is completed.
	WithOnComplete(func(ctx context.Context, response HTTPResponse, err error) error) HTTPRequest
	// WithOnSuccess method registers callback to be executed when the request is completed and `code >= 200 and <= 299`.
	WithOnSuccess(func(ctx context.Context, response HTTPResponse) error) HTTPRequest
	// WithOnError method registers callback to be executed when the request is completed and `code >= 400`.
	WithOnError(func(ctx context.Context, response HTTPResponse, err error) error) HTTPRequest
	// Send method sends defined request and returns response, mapped result and error.
	Send(ctx context.Context) (response HTTPResponse, result any, err error)
	SendOrErr(ctx context.Context) error
	// contains filtered or unexported methods
}

HTTPRequest is an immutable HTTP request.

func NewHTTPRequest

func NewHTTPRequest(sender Sender) HTTPRequest

NewHTTPRequest creates immutable HTTP request.

type HTTPResponse

type HTTPResponse interface {

	// Result method returns the response mapped as a data type, if any.
	Result() any
	// contains filtered or unexported methods
}

HTTPResponse with response mapped to the Result() value.

type NoResult

type NoResult struct{}

NoResult type.

type ParallelAPIRequests

type ParallelAPIRequests []Sendable

func Parallel

func Parallel(requests ...Sendable) ParallelAPIRequests

Parallel wraps parallel requests to one Sendable interface.

func (ParallelAPIRequests) SendOrErr

func (v ParallelAPIRequests) SendOrErr(ctx context.Context) error

type ReqDefinitionError

type ReqDefinitionError struct {
	// contains filtered or unexported fields
}

ReqDefinitionError can be used as the Sendable interface. So the error will be returned when you try to send the request. This simplifies usage, the error is checked only once, in one place.

func (ReqDefinitionError) SendOrErr

func (v ReqDefinitionError) SendOrErr(_ context.Context) error

func (ReqDefinitionError) Unwrap

func (v ReqDefinitionError) Unwrap() error

type Result

type Result = any

Result - any value.

type RunGroup

type RunGroup struct {
	// contains filtered or unexported fields
}

RunGroup allows scheduling requests by Add method and then send them concurrently by the RunAndWait method.

The sending will stop when the first error occurs. The first error will be returned from the RunAndWait method.

If you need to send requests immediately, or if you want to wait and collect all errors, use client.WaitGroup instead.

func NewRunGroup

func NewRunGroup(ctx context.Context, sender Sender) *RunGroup

NewRunGroup creates a new RunGroup.

func RunGroupWithLimit

func RunGroupWithLimit(ctx context.Context, sender Sender, limit int64) *RunGroup

RunGroupWithLimit creates a new RunGroup with given concurrent requests limit.

func (*RunGroup) Add

func (g *RunGroup) Add(request Sendable)

Add request for sending. The request will be sent on call of the RunAndWait method. Additional requests can be added using the Add method (for example from a request callback), even if RunAndWait has already been called, but is not yet finished.

func (*RunGroup) RunAndWait

func (g *RunGroup) RunAndWait() error

RunAndWait starts sending requests and waits for the result. After the first error sending stops and the error is returned.

Additional requests can be added using the Add method (for example from a request callback), even if RunAndWait has already been called, but is not yet finished.

type Sendable

type Sendable interface {
	SendOrErr(ctx context.Context) error
}

Sendable is HTTPRequest or APIRequest.

func NewReqDefinitionError

func NewReqDefinitionError(err error) Sendable

type Sender

type Sender interface {
	// Send method sends defined request and returns response.
	// Type of the return value "result" must be the same as type of the HTTPRequest.ResultDef(), otherwise panic will occur.
	//   In Go, this rule cannot be written using generic types yet, methods cannot have generic types.
	//   Send[R Result](ctx context.Context, request HTTPRequest[R]) (rawResponse *http.Response, result R, error error)
	Send(ctx context.Context, request HTTPRequest) (rawResponse *http.Response, result any, err error)
}

Sender represents an HTTP client, the client.Client is a default implementation using the standard net/http package.

type WaitGroup

type WaitGroup struct {
	// contains filtered or unexported fields
}

WaitGroup allows sending requests concurrently using Send method and wait until all requests are completed using the Wait method.

The request starts immediately after calling the Send method. If an error occurs, sending will not stop, all requests will be sent. Wait method at the end returns all errors that have occurred, if any.

If you need to schedule requests and send them later, or if you want to stop at the first error, use client.RunGroup instead.

func NewWaitGroup

func NewWaitGroup(ctx context.Context) *WaitGroup

NewWaitGroup creates new WaitGroup.

func NewWaitGroupWithLimit

func NewWaitGroupWithLimit(ctx context.Context, limit int64) *WaitGroup

NewWaitGroupWithLimit creates new WaitGroup with given concurrent requests limit.

func (*WaitGroup) Send

func (g *WaitGroup) Send(request Sendable)

Send a concurrent request.

func (*WaitGroup) Wait

func (g *WaitGroup) Wait() error

Wait for all requests to complete. All errors that have occurred will be returned.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL