transport

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2024 License: MIT Imports: 11 Imported by: 5

README

Go HTTP transports & middlewares for outgoing HTTP requests

Chaining transports is a pattern originally inspired by this article https://dev.to/stevenacoffman/tripperwares-http-client-middleware-chaining-roundtrippers-3o00. This pattern is similar to middleware pattern which is used to enrich a context of http request coming to your application. There are multiple use-cases where this pattern comes handy such as request logging, caching, authentication and even implementation of retry mechanisms.

Examples

Set up HTTP client, which sets User-Agent, Authorization and TraceID headers automatically:

import (
    "github.com/go-chi/traceid"
)

authClient := http.Client{
    Transport: transport.Chain(
        http.DefaultTransport,
        transport.SetHeader("User-Agent", userAgent),
        transport.SetHeader("Authorization", authHeader),
        traceid.Transport,
    ),
    Timeout: 15 * time.Second,
}

Or debug all outgoing requests as curl globally within your application:

debugMode := os.Getenv("DEBUG") == "true"

http.DefaultTransport = transport.Chain(
    http.DefaultTransport,
    transport.If(debugMode, transport.LogRequests(transport.LogOptions{Concise: true, CURL: true})),
)

Authors

License

MIT license

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Chain

func Chain(base http.RoundTripper, mw ...func(http.RoundTripper) http.RoundTripper) *chain

Chain wraps given base RoundTripper, which is used to make HTTP requests (e.g. http.DefaultTransport) with RoundTripper middlewares.

The middlewares can print, debug or modify request/response headers, cookies, context timeouts etc.

Note: Per stdlib docs, RoundTrip should not modify the original request, except for consuming and closing the request's body. Thus, it's advised to clone the original request before modifying it, e.g. golang.org/x/oauth2: https://cs.opensource.google/go/x/oauth2/+/refs/tags/v0.13.0:transport.go;l=50.

A typical use case is to set User-Agent, Authorization or TraceID headers:

authClient := http.Client{
    Transport: transport.Chain(
        http.DefaultTransport,
        transport.SetHeader("User-Agent", userAgent),
        transport.SetHeader("Authorization", authHeader),
        transport.SetHeader("x-extra", "value"),
		transport.TraceID,
    ),
    Timeout: 15 * time.Second,
}

Or debug all outgoing requests in a debug mode:

http.DefaultTransport = transport.Chain(
	http.DefaultTransport,
	transport.LogRequests,
)

func CloneRequest added in v0.2.0

func CloneRequest(orig *http.Request) *http.Request

CloneRequest creates a shallow copy of a given request to comply with stdlib's http.RoundTripper contract:

RoundTrip should not modify the request, except for consuming and closing the Request's Body. RoundTrip may read fields of the request in a separate goroutine. Callers should not mutate or reuse the request until the Response's Body has been closed.

func DelayedRequest added in v0.5.0

func DelayedRequest(requestDelayMin, requestDelayMax time.Duration) func(http.RoundTripper) http.RoundTripper

DelayedRequest is a middleware that delays requests, useful when testing timeouts while waiting on a request to be sent upstream.

func DelayedResponse added in v0.5.0

func DelayedResponse(responseDelayMin, responseDelayMax time.Duration) func(http.RoundTripper) http.RoundTripper

DelayedResponse is a middleware that delays responses, useful when testing timeouts after upstream has processed the request, the response is hold back until the delay is over.

func If added in v0.3.0

func If(condition bool, transport func(http.RoundTripper) http.RoundTripper) func(http.RoundTripper) http.RoundTripper

If sets given transport if given condition is true. Otherwise it sets nil transport, which will be ignored.

Example:

http.DefaultTransport = transport.Chain(
  http.DefaultTransport,
  transport.If(debugMode, transport.LogRequests),
)

func LogRequests

func LogRequests(opts LogOptions) func(next http.RoundTripper) http.RoundTripper

func Retry

func Retry(baseTransport http.RoundTripper, maxRetries int) func(http.RoundTripper) http.RoundTripper

func SetHeader

func SetHeader(header string, value string) func(http.RoundTripper) http.RoundTripper

func SetHeaderFunc

func SetHeaderFunc(header string, fn func(req *http.Request) string) func(http.RoundTripper) http.RoundTripper

Types

type LogOptions added in v0.4.0

type LogOptions struct {
	Concise bool
	CURL    bool
}

type RoundTripFunc

type RoundTripFunc func(r *http.Request) (*http.Response, error)

RoundTripFunc, similar to http.HandlerFunc, is an adapter to allow the use of ordinary functions as http.RoundTrippers.

func (RoundTripFunc) RoundTrip

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error)

Jump to

Keyboard shortcuts

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