https

package
v0.0.20 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 20 Imported by: 11

Documentation

Overview

Copyright (c) APIMatic. All rights reserved.

Package https provides utilities and structures for handling API requests and responses using the HTTP protocol. Copyright (c) APIMatic. All rights reserved.

Copyright (c) APIMatic. All rights reserved.

Index

Constants

View Source
const (
	Indexed = iota
	UnIndexed
	Plain
	Csv
	Tsv
	Psv
)

Constants for different request retry options.

View Source
const ACCEPT_HEADER = "accept"
View Source
const AND_AUTH = "and"
View Source
const AUTHENTICATION_ERROR = "Authentication Error"
View Source
const AUTHORIZATION_HEADER = "authorization"
View Source
const CONTENT_LENGTH_HEADER = "content-length"
View Source
const CONTENT_TYPE_HEADER = "content-type"

Constants for commonly used HTTP headers and content types.

View Source
const FORM_URLENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded"
View Source
const INTERNAL_ERROR = "Internal Error"
View Source
const JSON_CONTENT_TYPE = "application/json"
View Source
const MULTIPART_CONTENT_TYPE = "multipart/form-data"
View Source
const OR_AUTH = "or"
View Source
const SINGLE_AUTH = "single"
View Source
const TEXT_CONTENT_TYPE = "text/plain; charset=utf-8"
View Source
const XML_CONTENT_TYPE = "application/xml"

Variables

View Source
var ArraySerializationOptionStrings = [...]string{
	"Indexed",
	"UnIndexed",
	"Plain",
	"Csv",
	"Tsv",
	"Psv",
}

Functions

func AddQuery added in v0.0.15

func AddQuery(req *http.Request, key, value string)

func GetTestingServer

func GetTestingServer() *httptest.Server

GetTestingServer creates and returns an httptest.Server instance for testing purposes.

func MergeHeaders

func MergeHeaders(headers, headersToMerge map[string]string)

MergeHeaders merges the headers from the `headersToMerge` map into the `headers` map. If a header with a key already exists in the `headers` map, it is skipped and not overwritten.

func ReadBytes

func ReadBytes(input io.Reader) ([]byte, error)

ReadBytes reads the data from the input io.Reader and returns it as a byte array. If there is an error while reading, it returns the error along with the byte array.

func SetHeaders

func SetHeaders(headers map[string]string, name, value string)

SetHeaders sets the header name and value in the provided headers map.

func Unescape added in v0.0.20

func Unescape(token string) string

Unescape unescapes a json pointer reference token string to the original representation

Types

type ApiError added in v0.0.16

type ApiError struct {
	Request    http.Request
	StatusCode int
	Headers    http.Header
	Body       []byte
	Message    string
}

ApiError is the base struct for all error responses from the server. It holds information about the original HTTP request, the status code, headers, and response body.

func (ApiError) Error added in v0.0.16

func (a ApiError) Error() string

type ApiResponse

type ApiResponse[T any] struct {
	Data     T              `json:"data"`
	Response *http.Response `json:"response"`
}

ApiResponse is a generic struct that represents an API response containing data and the HTTP response. The `Data` field holds the data of any type `T` returned by the API. The `Response` field contains the underlying HTTP response associated with the API call.

func NewApiResponse

func NewApiResponse[T any](data T, response *http.Response) ApiResponse[T]

NewApiResponse creates a new instance of ApiResponse. It takes the `data` of type `T` and the `response` as parameters, and returns an ApiResponse[T] struct.

type ArraySerializationOption added in v0.0.18

type ArraySerializationOption int

ArraySerializationOption represents the type for request array serialization options.

type AuthGroup added in v0.0.15

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

func NewAndAuth added in v0.0.15

func NewAndAuth(authGroup1, authGroup2 AuthGroup, moreAuthGroups ...AuthGroup) AuthGroup

func NewAuth added in v0.0.15

func NewAuth(key string) AuthGroup

func NewOrAuth added in v0.0.15

func NewOrAuth(authGroup1, authGroup2 AuthGroup, moreAuthGroups ...AuthGroup) AuthGroup

type AuthInterface added in v0.0.15

type AuthInterface interface {
	Validate() error
	Authenticator() HttpInterceptor
}

type CallBuilder

type CallBuilder interface {
	AppendPath(path string)
	AppendTemplateParam(param string)
	AppendTemplateParams(params any)
	AppendErrors(errors map[string]ErrorBuilder[error])
	BaseUrl(arg string)
	Method(httpMethodName string)

	Accept(acceptHeaderValue string)
	ContentType(contentTypeHeaderValue string)
	Header(name string, value any)
	CombineHeaders(headersToMerge map[string]string)
	QueryParam(name string, value any)
	QueryParams(parameters map[string]any)
	QueryParamWithArraySerializationOption(name string, value any, option ArraySerializationOption)
	QueryParamsWithArraySerializationOption(parameters map[string]any, option ArraySerializationOption)

	FormParam(name string, value any)
	FormParams(parameters map[string]any)
	FormParamWithArraySerializationOption(name string, value any, opt ArraySerializationOption)
	FormParamsWithArraySerializationOption(parameters map[string]any, opt ArraySerializationOption)

	FormData(fields FormParams)

	Text(body string)
	FileStream(file FileWrapper)
	Json(data any)

	InterceptRequest(interceptor func(httpRequest *http.Request) *http.Request)

	Call() (*HttpContext, error)
	CallAsJson() (*json.Decoder, *http.Response, error)
	CallAsText() (string, *http.Response, error)
	CallAsStream() ([]byte, *http.Response, error)
	Authenticate(authGroup AuthGroup)
	RequestRetryOption(option RequestRetryOption)
	ArraySerializationOption(option ArraySerializationOption)
	// contains filtered or unexported methods
}

CallBuilder is an interface that defines methods for building and executing HTTP requests for API calls.

type CallBuilderFactory

type CallBuilderFactory func(ctx context.Context, httpMethod, path string) CallBuilder

CallBuilderFactory is a function type used to create CallBuilder instances for making API calls.

func CreateCallBuilderFactory

func CreateCallBuilderFactory(
	baseUrlProvider baseUrlProvider,
	auth map[string]AuthInterface,
	httpClient HttpClient,
	retryConfig RetryConfiguration,
	option ArraySerializationOption,
) CallBuilderFactory

CreateCallBuilderFactory creates a new CallBuilderFactory function which creates a new CallBuilder using the provided inputs

type ErrorBuilder added in v0.0.16

type ErrorBuilder[T error] struct {
	Message          string
	TemplatedMessage string
	Unmarshaller     func(ApiError) T
}

func (ErrorBuilder[T]) Build added in v0.0.16

func (eb ErrorBuilder[T]) Build(httpctx HttpContext) error

type FileWrapper

type FileWrapper struct {
	File        []byte
	FileName    string
	FileHeaders http.Header
}

FileWrapper is a struct that represents a file along with its metadata such as the file content, file name, and file headers.

func GetFile

func GetFile(fileUrl string) (FileWrapper, error)

GetFile retrieves a file from the given fileUrl and returns it as a FileWrapper. It makes an HTTP GET request to the fileUrl to fetch the file's content and metadata.

type FormParam added in v0.0.11

type FormParam struct {
	Key     string
	Value   any
	Headers http.Header
}

FormParam is a struct that represents a key-value pair for form parameters. It contains the key, value, and headers associated with the form parameter.

type FormParams added in v0.0.13

type FormParams []FormParam

FormParams represents a collection of FormParam objects.

func (*FormParams) Add added in v0.0.13

func (fp *FormParams) Add(formParam FormParam)

Add appends a FormParam to the FormParams collection.

type HttpCallExecutor

type HttpCallExecutor func(request *http.Request) HttpContext

HttpCallExecutor is a function type that represents the execution of an HTTP call and returns the HTTP context.

func CallHttpInterceptors

func CallHttpInterceptors(
	interceptors []HttpInterceptor,
	client HttpCallExecutor,
) HttpCallExecutor

CallHttpInterceptors chains multiple HTTP interceptors together to create a composite HttpCallExecutor. The interceptors are applied in the reverse order of their appearance in the interceptors slice. Each interceptor gets a chance to process the request before passing it to the next interceptor in the chain, and finally, the original HttpCallExecutor is called to execute the HTTP call. The composite HttpCallExecutor is returned, which includes the logic of all the interceptors.

type HttpClient

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

HttpClient is an implementation of the HttpClientInterface.

func NewHttpClient

func NewHttpClient(httpConfig HttpConfiguration) HttpClient

NewHttpClient creates a new HttpClient with the provided HttpConfiguration and returns it. The HttpConfiguration is used to set configurations like timeout, transport and retry configuration settings for the HTTP client.

func (*HttpClient) Execute

func (c *HttpClient) Execute(request *http.Request) (*http.Response, error)

Execute sends an HTTP request using the HttpClient and returns the HTTP response or an error.

type HttpClientInterface

type HttpClientInterface interface {
	Execute(request *http.Request) *http.Response
}

HttpClientInterface defines an interface for an HTTP client that can execute HTTP requests and return HTTP responses.

type HttpConfiguration

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

HttpConfiguration holds the configuration options for the HTTP client.

func NewHttpConfiguration

func NewHttpConfiguration(options ...HttpConfigurationOptions) HttpConfiguration

NewHttpConfiguration creates a new HttpConfiguration with the provided options and returns it. The options parameter allows setting different configuration options for the HTTP client.

func (*HttpConfiguration) RetryConfiguration

func (h *HttpConfiguration) RetryConfiguration() RetryConfiguration

RetryConfiguration returns the configured retry configuration for the HTTP client.

func (*HttpConfiguration) Timeout

func (h *HttpConfiguration) Timeout() float64

Timeout returns the configured timeout value for the HTTP client.

func (*HttpConfiguration) Transport

func (h *HttpConfiguration) Transport() http.RoundTripper

Transport returns the configured custom HTTP transport for the HTTP client.

type HttpConfigurationOptions

type HttpConfigurationOptions func(*HttpConfiguration)

HttpConfigurationOptions is a function type that takes a pointer to HttpConfiguration as input and modifies it.

func WithRetryConfiguration

func WithRetryConfiguration(retryConfig RetryConfiguration) HttpConfigurationOptions

WithRetryConfiguration sets the retry configuration for the HTTP client.

func WithTimeout

func WithTimeout(timeout float64) HttpConfigurationOptions

WithTimeout sets the timeout for the HTTP client.

func WithTransport

func WithTransport(transport http.RoundTripper) HttpConfigurationOptions

WithTransport sets the custom HTTP transport for the HTTP client.

type HttpContext

type HttpContext struct {
	Request  *http.Request
	Response *http.Response
}

HttpContext represents the HTTP request and response.

func PassThroughInterceptor

func PassThroughInterceptor(
	req *http.Request,
	next HttpCallExecutor,
) HttpContext

PassThroughInterceptor is an HTTP interceptor that passes the request to the next HttpCallExecutor in the chain. It does not modify the request or response and acts as a no-operation interceptor.

type HttpInterceptor

type HttpInterceptor func(request *http.Request, next HttpCallExecutor) HttpContext

HttpInterceptor is a function type that represents an HTTP interceptor, which intercepts and processes an HTTP call.

type RequestRetryOption

type RequestRetryOption int

RequestRetryOption represents the type for request retry options.

const (
	Default RequestRetryOption = iota
	Enable
	Disable
)

Constants for different request retry options.

func (RequestRetryOption) String

func (r RequestRetryOption) String() string

String returns the string representation of the RequestRetryOption.

type RetryConfiguration

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

RetryConfiguration contains the settings for request retry behavior.

func NewRetryConfiguration

func NewRetryConfiguration(options ...RetryConfigurationOptions) RetryConfiguration

NewRetryConfiguration creates a new RetryConfiguration instance with the provided options.

func (*RetryConfiguration) BackoffFactor

func (r *RetryConfiguration) BackoffFactor() int64

BackoffFactor returns the backoff factor for exponential backoff.

func (*RetryConfiguration) GetRetryWaitTime

func (rc *RetryConfiguration) GetRetryWaitTime(
	maxWaitTime time.Duration,
	retryCount int64,
	response *http.Response,
	timeoutError error) time.Duration

GetRetryWaitTime calculates the wait time for the next retry attempt.

func (*RetryConfiguration) HttpMethodsToRetry

func (r *RetryConfiguration) HttpMethodsToRetry() []string

HttpMethodsToRetry returns the list of HTTP methods to retry on.

func (*RetryConfiguration) HttpStatusCodesToRetry

func (r *RetryConfiguration) HttpStatusCodesToRetry() []int64

HttpStatusCodesToRetry returns the list of HTTP status codes to retry on.

func (*RetryConfiguration) MaxRetryAttempts

func (r *RetryConfiguration) MaxRetryAttempts() int64

MaxRetryAttempts returns the maximum number of retry attempts allowed.

func (*RetryConfiguration) MaximumRetryWaitTime

func (r *RetryConfiguration) MaximumRetryWaitTime() time.Duration

MaximumRetryWaitTime returns the maximum wait time before giving up retrying.

func (*RetryConfiguration) RetryInterval

func (r *RetryConfiguration) RetryInterval() time.Duration

RetryInterval returns the interval between retries.

func (*RetryConfiguration) RetryOnTimeout

func (r *RetryConfiguration) RetryOnTimeout() bool

RetryOnTimeout returns whether to retry on timeouts.

func (*RetryConfiguration) ShouldRetry

func (rc *RetryConfiguration) ShouldRetry(retryRequestOption RequestRetryOption, httpMethod string) bool

ShouldRetry determines if the request should be retried based on the RetryConfiguration and request HTTP method.

type RetryConfigurationOptions

type RetryConfigurationOptions func(*RetryConfiguration)

RetryConfigurationOptions represents a function that modifies RetryConfiguration settings.

func WithBackoffFactor

func WithBackoffFactor(backoffFactor int64) RetryConfigurationOptions

WithBackoffFactor sets the backoff factor for exponential backoff.

func WithHttpMethodsToRetry

func WithHttpMethodsToRetry(httpMethodsToRetry []string) RetryConfigurationOptions

WithHttpMethodsToRetry sets the list of HTTP methods to retry on.

func WithHttpStatusCodesToRetry

func WithHttpStatusCodesToRetry(httpStatusCodesToRetry []int64) RetryConfigurationOptions

WithHttpStatusCodesToRetry sets the list of HTTP status codes to retry on.

func WithMaxRetryAttempts

func WithMaxRetryAttempts(maxRetryAttempts int64) RetryConfigurationOptions

WithMaxRetryAttempts sets the maximum number of retry attempts allowed.

func WithMaximumRetryWaitTime

func WithMaximumRetryWaitTime(maximumRetryWaitTime time.Duration) RetryConfigurationOptions

WithMaximumRetryWaitTime sets the maximum wait time before giving up retrying.

func WithRetryInterval

func WithRetryInterval(retryInterval time.Duration) RetryConfigurationOptions

WithRetryInterval sets the interval between retries.

func WithRetryOnTimeout

func WithRetryOnTimeout(retryOnTimeout bool) RetryConfigurationOptions

WithRetryOnTimeout sets whether to retry on timeouts.

Jump to

Keyboard shortcuts

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