httpx

package
v0.0.0-...-2b7dcb4 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2024 License: BSD-2-Clause Imports: 14 Imported by: 31

README

Package httpx

Package httpx provides a layer of convenience over "net/http". Specifically:

  1. httpx.Handler's return an error which makes handler implementations feel more idiomatic and reduces the chance of accidentally forgetting to return.

The most important part of package httpx is the Handler interface, which is defined as:

type Handler interface {
	ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}

Usage

In order to use the httpx.Handler interface, you need a compatible router. One is provided within this package that wraps gorilla mux.

r := httpx.NewRouter()
r.HandleFunc("/", func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	io.WriteString(w, `ok`)
	return nil
}).Methods("GET")

// Adapt the router to the http.Handler interface and insert a
// context.Background().
s := middleware.Background(r)

http.ListenAndServe(":8080", s)

Documentation

Overview

package httpx provides an extra layer of convenience over package http.

Index

Constants

This section is empty.

Variables

View Source
var DefaultHTTPClient = &http.Client{
	Transport: DefaultHTTPTransport,
}
View Source
var DefaultHTTPTransport = &http.Transport{
	Proxy: http.ProxyFromEnvironment,
	Dial: (&net.Dialer{
		Timeout:   15 * time.Second,
		KeepAlive: 90 * time.Second,
	}).Dial,
	TLSHandshakeTimeout: 3 * time.Second,
}

Functions

func EncodeError

func EncodeError(err error, rw http.ResponseWriter)

func Error

func Error(ctx context.Context, err error, rw http.ResponseWriter, r *http.Request)

func ErrorStatusCode

func ErrorStatusCode(err error) int
func Header(ctx context.Context, headerKey string) string

func NewJSONRequest

func NewJSONRequest(method, path string, v interface{}) (*http.Request, error)

NewJSONRequest generates a new http.Request with the body set to the json encoding of v.

func NotFound

func NotFound(ctx context.Context, w http.ResponseWriter, r *http.Request) error

NotFound is a HandlerFunc that just delegates off to http.NotFound.

func ParseURL

func ParseURL(baseURL *url.URL, path string) string

func RequestID

func RequestID(ctx context.Context) string

RequestID extracts a RequestID from a context.

func URLWithoutCreds

func URLWithoutCreds(u url.URL) string

Shows the URL without information about the current username and password

func Vars

func Vars(ctx context.Context) map[string]string

Vars extracts the route vars from a context.Context.

func WithHeader

func WithHeader(ctx context.Context, headerKey string, headerValue string) context.Context

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID inserts a RequestID into the context.

func WithRoute

func WithRoute(ctx context.Context, r *Route) context.Context

WithVars adds the current Route to the context.Context.

func WithVars

func WithVars(ctx context.Context, vars map[string]string) context.Context

WithVars adds the vars to the context.Context.

Types

type Client

type Client struct {
	Transport RoundTripper
}

Client is an extension of http.Client with context.Context support.

func NewClient

func NewClient(c *http.Client) *Client

NewClient returns a new Client instance that will use the given http.Client to perform round trips

func NewDefaultServiceClient

func NewDefaultServiceClient(serviceName string) *Client

func NewServiceClient

func NewServiceClient(serviceName string, c *http.Client) *Client

NewServiceClient returns an httpx.Client that has the following behavior:

  1. Request ids will be added to outgoing requests within the X-Request-Id header.
  2. Any 500 errors will be retried.

The optional *http.Client parameter can be used to override the default client.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request) (*http.Response, error)

Do performs the request and returns the response.

type HTTPError

type HTTPError struct {
	Path       string
	StatusCode int
}

HTTPError is for generic non-200 errors

func (*HTTPError) Error

func (e *HTTPError) Error() string

type Handler

type Handler interface {
	ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}

Handler is represents a Handler that can take a context.Context as the first argument.

type HandlerFunc

type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error

The HandlerFunc type is an adapter to allow the use of ordinary functions as httpx handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

func (HandlerFunc) ServeHTTPContext

func (f HandlerFunc) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error

ServeHTTPContext calls f(ctx, w, r)

type RequestIDTransport

type RequestIDTransport struct {
	Transport RoundTripper
}

RequestIDTransport is an http.RoundTripper implementation that adds the embedded request id to outgoing http requests.

func (*RequestIDTransport) RoundTrip

func (t *RequestIDTransport) RoundTrip(ctx context.Context, req *http.Request) (*http.Response, error)

type RetryTransport

type RetryTransport struct {
	*retry.Retrier
	MethodsToRetry map[string]bool
	Transport      RoundTripper
}

RetryTransport is an implementation of the RoundTripper interface that retries requests.

func NewRetryTransport

func NewRetryTransport(retrier *retry.Retrier, transport RoundTripper) *RetryTransport

NewRetryTransport returns a RetryTransport that will retry idempotent HTTP requests (GET/HEAD) using the given retrier.

func (*RetryTransport) RoundTrip

func (t *RetryTransport) RoundTrip(ctx context.Context, req *http.Request) (*http.Response, error)

type RetryableHTTPError

type RetryableHTTPError struct {
	Path       string
	StatusCode int
}

RetryableHTTPError is used to represent error codes that can be allowed to retry

func (*RetryableHTTPError) Error

func (e *RetryableHTTPError) Error() string

type RoundTripper

type RoundTripper interface {
	RoundTrip(context.Context, *http.Request) (*http.Response, error)
}

type Route

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

Route wraps a mux.Route.

func RouteFromContext

func RouteFromContext(ctx context.Context) *Route

RouteFromContext extracts the current Route from a context.Context.

func (*Route) GetName

func (r *Route) GetName() string

GetName returns the name for the route, if any.

func (*Route) GetPathTemplate

func (r *Route) GetPathTemplate() string

Returns the path template for this route, if any.

func (*Route) Handler

func (r *Route) Handler(h Handler) *Route

Handler sets the httpx.Handler for this route.

func (*Route) HandlerFunc

func (r *Route) HandlerFunc(f func(context.Context, http.ResponseWriter, *http.Request) error) *Route

HandlerFunc sets the httpx.Handler for this route.

func (*Route) Methods

func (r *Route) Methods(methods ...string) *Route

Methods adds a matcher for HTTP methods. It accepts a sequence of one or more methods to be matched, e.g.: "GET", "POST", "PUT".

func (*Route) Name

func (r *Route) Name(name string) *Route

Name sets the name for the route, used to build URLs. If the name was registered already it will be overwritten.

func (*Route) URL

func (r *Route) URL(pairs ...string) (*url.URL, error)

See mux.Route.URL.

func (*Route) URLPath

func (r *Route) URLPath(pairs ...string) (*url.URL, error)

See mux.Route.URLPath.

type Router

type Router struct {
	// NotFoundHandler is a Handler that will be called when a route is not
	// found.
	NotFoundHandler Handler
	// contains filtered or unexported fields
}

Router is an httpx.Handler router.

func NewRouter

func NewRouter() *Router

NewRouter returns a new Router instance.

func (*Router) Handle

func (r *Router) Handle(path string, h Handler) *Route

Handle registers a new route with a matcher for the URL path

func (*Router) HandleFunc

func (r *Router) HandleFunc(path string, f func(context.Context, http.ResponseWriter, *http.Request) error) *Route

HandleFunc registers a new route with a matcher for the URL path

func (*Router) Handler

func (r *Router) Handler(req *http.Request) (route *Route, h Handler, vars map[string]string)

Handler returns a Handler that can be used to serve the request. Most of this is pulled from http://goo.gl/tyxad8.

func (*Router) Headers

func (r *Router) Headers(pairs ...string) *Route

Header adds a route that will be used if the header value matches.

func (*Router) Match

func (r *Router) Match(f func(*http.Request) bool, h Handler)

Match adds a route that will be matched if f returns true.

func (*Router) Path

func (r *Router) Path(path string) *Route

Path registers a new route with a matcher for the URL path.

func (*Router) ServeHTTPContext

func (r *Router) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, req *http.Request) error

ServeHTTPContext implements the Handler interface.

type Transport

type Transport struct {
	*http.Client
}

Transport is an implementation of the RoundTripper interface that uses an http.Client from the standard lib.

func (*Transport) RoundTrip

func (t *Transport) RoundTrip(ctx context.Context, req *http.Request) (*http.Response, error)

TODO: add support for context.Context cancellations

Directories

Path Synopsis
package errors provides error handling primitives in a request context.
package errors provides error handling primitives in a request context.

Jump to

Keyboard shortcuts

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