nxhttp

package module
v0.0.0-...-6f97f1c Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2026 License: MIT Imports: 15 Imported by: 0

README

nxhttp

Godoc Reference Pipeline Status

TODO: description

Licensing

All code in this repository is licensed under the MIT license.

Documentation

Overview

Package nxhttp . TODO: document

Example
package main

import (
	"context"
	"crypto/tls"
	"net/http"
	"time"

	"github.com/matthewpi/nxhttp"
)

func main() {
	_ = nxhttp.NewClient(
		// Client options
		nxhttp.WithTransport(func(t *http.Transport) {
			t.TLSClientConfig = &tls.Config{}
		}),
		nxhttp.WithTimeout(15*time.Second),
		// Regular options
		nxhttp.MaxAttempts(5),
		nxhttp.OnError(func(_ context.Context, err error) error { return err }),
	)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func UseLastResponse

func UseLastResponse(*http.Request, []*http.Request) error

UseLastResponse disables the following of redirects. This function is designed to be used with CheckRedirect.

nxhttp.CheckRedirect(nxhttp.UseLastResponse)

Types

type BodyFunc

type BodyFunc func() (io.ReadCloser, error)

BodyFunc is a function that can be used with http.Request.GetBody.

The net/http package uses it for allowing request bodies to be sent even through redirects, however we use it to allow for retrying failed requests.

func GetBody

func GetBody(v any) (BodyFunc, int64, error)

GetBody returns a BodyFunc and size for the given body `v`. If `v` is not a recognized type, an error will be returned.

type CheckRedirectFunc

type CheckRedirectFunc func(req *http.Request, via []*http.Request) error

CheckRedirectFunc is the type of the function for the `CheckRedirect` field on an http.Client.

type Client

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

Client is an HTTP client.

func FromClient

func FromClient(h *http.Client, opts ...Option) *Client

FromClient constructs a Client using an existing *http.Client and any provided Option.

If you are able, it is preferred for users to construct a Client using NewClient. You can use ClientOption to much more easily configure the underlying *http.Client, especially if you need a custom *http.Transport and not just a custom http.RoundTripper.

Example
package main

import (
	"net/http"
	"net/http/httptest"

	"github.com/matthewpi/nxhttp"
)

func main() {
	ts := httptest.NewServer(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			_, _ = w.Write([]byte("Hello, world!"))
		}),
	)
	defer ts.Close()

	_ = nxhttp.FromClient(ts.Client())
}

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient constructs a Client using any provided ClientOption.

func (*Client) Do

func (c *Client) Do(req *Request, opts ...RequestOption) (*Response, error)

Do sends an HTTP request and returns an HTTP response.

type ClientOption

type ClientOption interface {
	// contains filtered or unexported methods
}

ClientOption for an *http.Client.

type ClientOptionFunc

type ClientOptionFunc func(o *clientOptions)

ClientOptionFunc type is an adapter to allow the use of ordinary functions as a ClientOption. If f is a function with the appropriate signature, `ClientOptionFunc(f)` is a ClientOption that calls f.

func CheckRedirect

func CheckRedirect(fn CheckRedirectFunc) ClientOptionFunc

CheckRedirect sets the policy for handling redirects.

func SetTransport

func SetTransport(t *http.Transport) ClientOptionFunc

SetTransport sets the underlying *http.Transport that will be used.

If you don't already have an *http.Transport available, consider using WithTransport instead.

NOTE: SetTransport can be used alongside WithTransport as long as WithTransport is called after SetTransport. Calls to SetTransport completely replace the *http.Transport used by the client.

Example
package main

import (
	"crypto/tls"
	"net/http"

	"github.com/matthewpi/nxhttp"
)

func main() {
	t := http.DefaultTransport.(*http.Transport).Clone()
	t.TLSClientConfig = &tls.Config{
		// Just as an example.
	}

	_ = nxhttp.NewClient(nxhttp.SetTransport(t))
}

func WithCookieJar

func WithCookieJar(jar http.CookieJar) ClientOptionFunc

WithCookieJar sets the http.CookieJar used by the *http.Client.

func WithRoundTripper

func WithRoundTripper(rtFunc func(http.RoundTripper) http.RoundTripper) ClientOptionFunc

WithRoundTripper sets the underlying http.RoundTripper that will be used by the *http.Client.

This option was designed to work with WithTransport to allow the easy configuration of an *http.Transport but also the ability to wrap it with a http.RoundTripper. Such as for use with OpenTelemetry via the otelhttp library as an example.

Example
package main

import (
	"net/http"

	"github.com/matthewpi/nxhttp"
)

func main() {
	_ = nxhttp.NewClient(
		nxhttp.WithRoundTripper(func(rt http.RoundTripper) http.RoundTripper {
			// NOTE: the following line is commented-out to avoid this library
			// depending on OpenTelemetry just for an example.

			// return otelhttp.NewTransport(rt)
			return rt
		}),
	)
}

func WithTimeout

func WithTimeout(d time.Duration) ClientOptionFunc

WithTimeout sets the timeout used by the *http.Client.

func WithTransport

func WithTransport(fn func(t *http.Transport)) ClientOptionFunc

WithTransport sets the underlying *http.Transport that will be used.

If you already have or prefer to construct your own *http.Transport, you can use SetTransport instead.

Example
package main

import (
	"crypto/tls"
	"net/http"

	"github.com/matthewpi/nxhttp"
)

func main() {
	_ = nxhttp.NewClient(
		nxhttp.WithTransport(func(t *http.Transport) {
			t.TLSClientConfig = &tls.Config{
				// Just as an example.
			}
		}),
	)
}

type ContentError

type ContentError struct {
	// Header that triggered the error.
	Header httpheader.Key
	// Value of the header in the response.
	Value string
	// Allowed or expected values for the header.
	Allowed []string
}

ContentError indicates an HTTP response contained an unexpected `Content-*` header.

func NewContentError

func NewContentError(key httpheader.Key, value string, allowed ...string) ContentError

NewContentError returns a new ContentError.

func (ContentError) Error

func (e ContentError) Error() string

Error returns an error message and satisfies the [error] interface.

func (ContentError) LogValue

func (e ContentError) LogValue() slog.Value

LogValue returns an slog.Value and satisfies the slog.LogValuer interface.

type ErrorFunc

type ErrorFunc func(context.Context, error) error

ErrorFunc . TODO: document

type ErrorResponseFunc

type ErrorResponseFunc func(context.Context, *Response) error

ErrorResponseFunc . TODO: document

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option for an Client.

type OptionFunc

type OptionFunc func(o *options)

OptionFunc type is an adapter to allow the use of ordinary functions as an Option. If f is a function with the appropriate signature, `OptionFunc(f)` is an Option that calls f.

func MaxAttempts

func MaxAttempts(maxAttempts uint) OptionFunc

MaxAttempts sets the maximum number of attempts that can occur. If set to 0 the maximum number of attempts will be unlimited.

func MaxRetryAfter

func MaxRetryAfter(d time.Duration) OptionFunc

MaxRetryAfter . TODO: document

func MinRetryAfter

func MinRetryAfter(d time.Duration) OptionFunc

MinRetryAfter . TODO: document

func OnError

func OnError(fn ErrorFunc) OptionFunc

OnError . TODO: document

func OnErrorResponse

func OnErrorResponse(fn ErrorResponseFunc) OptionFunc

OnErrorResponse . TODO: document

NOTE: consuming the response body in this function prevents it from being used by the main response handler. If you must consume the response body here, consider buffering and making it available by resetting `Body` on the response.

func WithDefaultHeader

func WithDefaultHeader(k httpheader.Key, v string) OptionFunc

WithDefaultHeader sets a default header for all HTTP requests.

func WithDefaultHeaders

func WithDefaultHeaders(h map[httpheader.Key]string) OptionFunc

WithDefaultHeaders sets the default headers for all HTTP requests.

type ReadOpener

type ReadOpener interface {
	// Open opens a new reader.
	Open() (io.ReadCloser, error)
}

ReadOpener is an interface for anything that can open a new io.ReadCloser.

func ReadOpenerFor

func ReadOpenerFor(fn BodyFunc, n int64) ReadOpener

ReadOpenerFor creates a new ReadOpener that uses fn as the opener and n for the size. If the size of the data is unknown, use `-1` as the value for n. Only use `0` as the value for n if the length of the data from the reader is actually 0.

type Request

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

Request . TODO: document

func NewRequest

func NewRequest(ctx context.Context, method, url string, body any) (*Request, error)

NewRequest returns a new Request given a method, URL, and optional body.

func (*Request) AddHeader

func (r *Request) AddHeader(key httpheader.Key, value string)

AddHeader is like http.Header.Add, but the key must already be in httpheader.Canonicalize form.

func (*Request) DelHeader

func (r *Request) DelHeader(key httpheader.Key)

DelHeader is like http.Header.Del, but the key must already be in httpheader.Canonicalize form.

func (*Request) SetBody

func (r *Request) SetBody(v any) (err error)

SetBody sets the body on the Request.

func (*Request) SetHeader

func (r *Request) SetHeader(key httpheader.Key, value string)

SetHeader is like http.Header.Set, but the key must already be in httpheader.Canonicalize form.

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext returns wrapped Request with a shallow copy of r with its context changed to ctx. The provided ctx must be non-nil.

func (*Request) WriteTo

func (r *Request) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface.

type RequestError

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

RequestError is returned if the request fails to be done, i.e. the server is never reached.

func (RequestError) Error

func (e RequestError) Error() string

Error returns an error message and satisfies the [error] interface.

func (RequestError) LogValue

func (e RequestError) LogValue() slog.Value

LogValue returns an slog.Value and satisfies the slog.LogValuer interface.

func (RequestError) Unwrap

func (e RequestError) Unwrap() error

Unwrap returns the underlying [error] that caused the RequestError.

type RequestOption

type RequestOption interface {
	// contains filtered or unexported methods
}

RequestOption for an Request.

type RequestOptionFunc

type RequestOptionFunc func(o *requestOptions)

RequestOptionFunc type is an adapter to allow the use of ordinary functions as a RequestOption. If f is a function with the appropriate signature, `RequestOptionFunc(f)` is a RequestOption that calls f.

func WithRequestRoundTripper

func WithRequestRoundTripper(fn func(http.RoundTripper) http.RoundTripper) RequestOptionFunc

WithRequestRoundTripper sets the underlying http.RoundTripper that will be used for an individual request.

func WithRequestTransport

func WithRequestTransport(fn func(t *http.Transport)) RequestOptionFunc

WithRequestTransport sets the underlying *http.Transport that will be used for an individual request.

type Response

type Response struct {
	*http.Response
}

Response represents the response from an HTTP request.

The Client return Responses from servers once the response headers have been received. The response body is streamed on demand as the Body field is read.

func (*Response) Close

func (r *Response) Close() error

Closes the body of r.

func (*Response) GetHeader

func (r *Response) GetHeader(key httpheader.Key) string

GetHeader is like http.Header.Get, but the key must already be in httpheader.Key form.

type SeekableFile

type SeekableFile interface {
	fs.File
	io.Seeker
}

SeekableFile is an interface for an fs.File that also implements io.Seeker.

type StatusError

type StatusError struct {
	// Data from the HTTP response.
	Data []byte

	// StatusCode is the status code from the [Response] that caused this
	// error.
	StatusCode int

	// Expected is the status code we expected to see in the [Response] but
	// we got [StatusCode] instead.
	Expected int
}

StatusError indicates an HTTP request failure with a status code from a remote HTTP server.

func AsStatusError

func AsStatusError(err error) (StatusError, bool)

AsStatusError attempts to recursively map err to a StatusError, even if it has been wrapped.

Internally, this uses errors.As and is provided as a convenience.

func NewStatusError

func NewStatusError(res *Response, expected int) StatusError

NewStatusError returns a new StatusError.

func (StatusError) Error

func (e StatusError) Error() string

Error returns an error message and satisfies the [error] interface.

func (StatusError) LogValue

func (e StatusError) LogValue() slog.Value

LogValue returns an slog.Value and satisfies the slog.LogValuer interface.

Directories

Path Synopsis
Package httpheader provides constantly typed HTTP headers in their canonicalized form to avoid additional string allocations and the possibility of typos.
Package httpheader provides constantly typed HTTP headers in their canonicalized form to avoid additional string allocations and the possibility of typos.

Jump to

Keyboard shortcuts

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