httpc

package module
v1.0.18 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2023 License: Apache-2.0 Imports: 18 Imported by: 1

README

A simple wrapper around the default Go http client optimized for ease-of-use

Github Release GoDoc Go Report Card Build/Test Status CodeQL

This package wraps the Go standard http client, providing a simplified interaction model using method chaining and additional capabilities such as optional in-flow validation against an OpenAPI specification.

Features

  • Simple, method chaining based interface for HTTP client requests
  • Simulation of request delays
  • Validation of request + response against OpenAPI specification
  • Customization of HTTP client via functional parameter
  • Back-Off-Retry concept to automatically retry requests if required

Installation

go get -u github.com/fako1024/httpc

Examples

Perform simple HTTP GET request
err := httpc.New("GET", "http://example.org").Run()
if err != nil {
	log.Fatalf("error performing GET request: %s", err)
}
Perform HTTP GET request and parse the result as JSON into a struct
var res = struct {
	Status int
	Message string
}{}
err := httpc.New("GET", "http://example.org").
	ParseJSON(&res).
	Run()
if err != nil {
	log.Fatalf("error performing GET request: %s", err)
}
Perform HTTPS POST request with a simple body, disabling certificate validation and copying the response to a bytes.Buffer
buf := new(bytes.Buffer)
err := httpc.New("POST", "https://example.org").
	SkipCertificateVerification().
	Body([]byte{0x1, 0x2}).
	ParseFn(httpc.Copy(buf)).
	Run()

if err != nil {
    log.Fatalf("error performing POST request: %s", err)
}

fmt.Println(buf.String())
Perform HTTPS GET request (with query parameters + headers + basic auth), validating request and response against OpenAPIv3 specification
openAPIFileData, err := os.ReadFile("/tmp/openapi.json")
if err != nil {
	log.Fatalf("Error opening OpenAPI specification file: %s", err)
}

err = httpc.New("GET", "https://example.org").
	SkipCertificateVerification().
	QueryParams(httpc.Params{
		"param": "test",
	}).
	Headers(httpc.Params{
		"X-HEADER-TEST": "test",
	}).
	AuthBasic("username", "password").
	OpenAPIValidationFileData(openAPIFileData).
	Run()

if err != nil {
	log.Fatalf("error performing GET request: %s", err)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Copy added in v1.0.2

func Copy(w io.Writer) func(resp *http.Response) error

Copy copies the response body into any io.Writer

func ParseCAChain added in v1.0.7

func ParseCAChain(caCert []byte) ([]*x509.Certificate, error)

ParseCAChain takes a file of PEM encoded things and returns the CERTIFICATEs in order taken and adapted from crypto/tls

func ParseJSON added in v1.0.2

func ParseJSON(v interface{}) func(resp *http.Response) error

ParseJSON parses the response body as JSON into a struct

func ParseXML added in v1.0.5

func ParseXML(v interface{}) func(resp *http.Response) error

ParseXML parses the response body as XML into a struct

func ParseYAML added in v1.0.2

func ParseYAML(v interface{}) func(resp *http.Response) error

ParseYAML parses the response body as YAML into a struct

Types

type Encoder added in v1.0.5

type Encoder interface {

	// Encode denotes a generic encoder function / method, usually a Marshal() function
	Encode() ([]byte, error)

	// ContentType provides an automated way to retrieve / set the content-type header
	ContentType() string
}

Encoder denotes a generic encoder, including an encoding function and content-type getter

type HTTPError added in v1.0.15

type HTTPError struct {
	Code     int
	Message  interface{}
	Internal error // Stores the error returned by an external dependency
}

HTTPError represents an error that occurred while handling a request Identical to struct used in labstack/echo

type Intervals added in v1.0.5

type Intervals = []time.Duration

Intervals is an alias for a list of durations / time intervals

type JSONEncoder added in v1.0.5

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

JSONEncoder provdes encoding to JSON

func (JSONEncoder) ContentType added in v1.0.5

func (e JSONEncoder) ContentType() string

ContentType fulfills the Encoder interface, providing the required content-type header

func (JSONEncoder) Encode added in v1.0.5

func (e JSONEncoder) Encode() ([]byte, error)

Encode fulfills the Encoder interface, performing the actual encoding

type Params

type Params = map[string]string

Params is an alias for a map of string key / value pairs

type Request

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

Request represents a generic web request for quick execution, providing access to method, URL parameters, headers, the body and an optional 1st class function used to parse the result

func New

func New(method, uri string) *Request

New instantiates a new http client

func NewWithClient added in v1.0.9

func NewWithClient(method, uri string, hc *http.Client) *Request

NewWithClient instantiates a new httpc request with custom http client This eases testing and client interception

func (*Request) AcceptedResponseCodes

func (r *Request) AcceptedResponseCodes(acceptedResponseCodes []int) *Request

AcceptedResponseCodes defines a set of accepted HTTP response codes for the client call

func (*Request) AuthBasic added in v1.0.8

func (r *Request) AuthBasic(user, password string) *Request

AuthBasic sets parameters to perform basic authentication

func (*Request) AuthBearer added in v1.0.14

func (r *Request) AuthBearer(token string) *Request

AuthBearer sets parameters to perform bearer token authentication, setting "Authorization: Bearer <token>"

func (*Request) AuthToken added in v1.0.14

func (r *Request) AuthToken(prefix, token string) *Request

AuthToken sets parameters to perform any token-based authentication, setting "Authorization: <prefix> <token>"

func (*Request) Body

func (r *Request) Body(body []byte) *Request

Body sets the body for the client call Note: Any existing body is overwritten

func (*Request) ClientCertificates added in v1.0.1

func (r *Request) ClientCertificates(clientCert, clientKey, caCert []byte) (*Request, error)

ClientCertificates sets client certificates from memory

func (*Request) ClientCertificatesFromFiles added in v1.0.1

func (r *Request) ClientCertificatesFromFiles(certFile, keyFile, caFile string) (*Request, error)

ClientCertificatesFromFiles sets client certificates from files

func (*Request) ClientCertificatesFromInstance added in v1.0.7

func (r *Request) ClientCertificatesFromInstance(clientCertWithKey tls.Certificate, caChain []*x509.Certificate) (*Request, error)

ClientCertificatesFromInstance sets the client certificates from a cert instance

func (*Request) Delay

func (r *Request) Delay(delay time.Duration) *Request

Delay sets an artificial delay for the client call

func (*Request) Encode added in v1.0.5

func (r *Request) Encode(encoder Encoder) *Request

Encode encodes and sets the body for the client call using an arbitrary encoder

func (*Request) EncodeJSON added in v1.0.5

func (r *Request) EncodeJSON(v interface{}) *Request

EncodeJSON encodes and sets the body for the client call using JSON encoding

func (*Request) EncodeXML added in v1.0.5

func (r *Request) EncodeXML(v interface{}) *Request

EncodeXML encodes and sets the body for the client call using XML encoding

func (*Request) EncodeYAML added in v1.0.5

func (r *Request) EncodeYAML(v interface{}) *Request

EncodeYAML encodes and sets the body for the client call using YAML encoding

func (*Request) ErrorFn added in v1.0.2

func (r *Request) ErrorFn(errorFn func(*http.Response) error) *Request

ErrorFn sets a parsing function for results not handled by ParseFn

func (*Request) GetBody

func (r *Request) GetBody() []byte

GetBody returns the body of the request

func (*Request) GetMethod

func (r *Request) GetMethod() string

GetMethod returns the method of the request

func (*Request) GetURI

func (r *Request) GetURI() string

GetURI returns the URI of the request

func (*Request) Headers

func (r *Request) Headers(headers Params) *Request

Headers sets the headers for the client call Note: Any existing headers are overwritten / removed

func (*Request) HostName

func (r *Request) HostName(host string) *Request

HostName sets an explicit hostname for the client call

func (*Request) ModifyHTTPClient

func (r *Request) ModifyHTTPClient(fn func(*http.Client)) *Request

ModifyHTTPClient executes any function / allows setting parameters of the underlying HTTP client before the actual request is made

func (*Request) ModifyRequest added in v1.0.5

func (r *Request) ModifyRequest(fn func(*http.Request) error) *Request

ModifyRequest allows the caller to call any methods or other functions on the http.Request prior to execution of the call

func (*Request) OpenAPIValidationFileData

func (r *Request) OpenAPIValidationFileData(fileData []byte) *Request

OpenAPIValidationFileData sets an OpenAPI validation file for the client call using a byte slice (containing the raw JSON file data)

func (*Request) ParseFn

func (r *Request) ParseFn(parseFn func(*http.Response) error) *Request

ParseFn sets a generic parsing function for the result of the client call

func (*Request) ParseJSON added in v1.0.5

func (r *Request) ParseJSON(v interface{}) *Request

ParseJSON parses the result of the client call as JSON

func (*Request) ParseXML added in v1.0.5

func (r *Request) ParseXML(v interface{}) *Request

ParseXML parses the result of the client call as XML

func (*Request) ParseYAML added in v1.0.5

func (r *Request) ParseYAML(v interface{}) *Request

ParseYAML parses the result of the client call as YAML

func (*Request) QueryParams

func (r *Request) QueryParams(queryParams Params) *Request

QueryParams sets the URL / query parameters for the client call Note: Any existing URL / query parameters are overwritten / removed

func (*Request) RetryBackOff added in v1.0.5

func (r *Request) RetryBackOff(intervals Intervals) *Request

RetryBackOff sets back-off intervals and attempts the call multiple times

func (*Request) RetryBackOffErrFn added in v1.0.6

func (r *Request) RetryBackOffErrFn(fn func(*http.Response, error) bool) *Request

RetryBackOffErrFn sets an assessment function to decide wether an error or status code is deemed as a reason to retry the call. Note: both the response and the error may be nil (depending on the reason for the retry) so proper checks must be ensured

func (*Request) RetryEventFn added in v1.0.14

func (r *Request) RetryEventFn(fn func(int, *http.Response, error)) *Request

RetryEventFn sets an event handler / function that gets triggered upon a retry, providing the HTTP response and error that causes the retry. Note: both the response and the error may be nil (depending on the reason for the retry) so proper checks must be ensured

func (*Request) Run

func (r *Request) Run() error

Run executes a request

func (*Request) RunWithContext added in v1.0.5

func (r *Request) RunWithContext(ctx context.Context) error

RunWithContext executes a request using a specific context

func (*Request) SkipCertificateVerification

func (r *Request) SkipCertificateVerification() *Request

SkipCertificateVerification will accept any SSL certificate

func (*Request) Timeout

func (r *Request) Timeout(timeout time.Duration) *Request

Timeout sets timeout for the client call

func (*Request) Transport added in v1.0.2

func (r *Request) Transport(transport http.RoundTripper) *Request

Transport forces a specific transport for the HTTP client (e.g. http.DefaultTransport in order to support standard gock flows)

type XMLEncoder added in v1.0.5

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

XMLEncoder provdes encoding to XML

func (XMLEncoder) ContentType added in v1.0.5

func (e XMLEncoder) ContentType() string

ContentType fulfills the Encoder interface, providing the required content-type header

func (XMLEncoder) Encode added in v1.0.5

func (e XMLEncoder) Encode() ([]byte, error)

Encode fulfills the Encoder interface, performing the actual encoding

type YAMLEncoder added in v1.0.5

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

YAMLEncoder provdes encoding to YAML

func (YAMLEncoder) ContentType added in v1.0.5

func (e YAMLEncoder) ContentType() string

ContentType fulfills the Encoder interface, providing the required content-type header

func (YAMLEncoder) Encode added in v1.0.5

func (e YAMLEncoder) Encode() ([]byte, error)

Encode fulfills the Encoder interface, performing the actual encoding

Jump to

Keyboard shortcuts

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