http

package
v0.14.0-openmesh Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2023 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package http provides a general purpose HTTP binding for endpoints.

Index

Examples

Constants

View Source
const (
	// ContextKeyRequestMethod is populated in the context by
	// PopulateRequestContext. Its value is r.Method.
	ContextKeyRequestMethod contextKey = iota

	// ContextKeyRequestURI is populated in the context by
	// PopulateRequestContext. Its value is r.RequestURI.
	ContextKeyRequestURI

	// ContextKeyRequestPath is populated in the context by
	// PopulateRequestContext. Its value is r.URL.Path.
	ContextKeyRequestPath

	// ContextKeyRequestProto is populated in the context by
	// PopulateRequestContext. Its value is r.Proto.
	ContextKeyRequestProto

	// ContextKeyRequestHost is populated in the context by
	// PopulateRequestContext. Its value is r.Host.
	ContextKeyRequestHost

	// ContextKeyRequestRemoteAddr is populated in the context by
	// PopulateRequestContext. Its value is r.RemoteAddr.
	ContextKeyRequestRemoteAddr

	// ContextKeyRequestXForwardedFor is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-For").
	ContextKeyRequestXForwardedFor

	// ContextKeyRequestXForwardedProto is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-Proto").
	ContextKeyRequestXForwardedProto

	// ContextKeyRequestAuthorization is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("Authorization").
	ContextKeyRequestAuthorization

	// ContextKeyRequestReferer is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("Referer").
	ContextKeyRequestReferer

	// ContextKeyRequestUserAgent is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("User-Agent").
	ContextKeyRequestUserAgent

	// ContextKeyRequestXRequestID is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("X-Request-Id").
	ContextKeyRequestXRequestID

	// ContextKeyRequestAccept is populated in the context by
	// PopulateRequestContext. Its value is r.Header.Get("Accept").
	ContextKeyRequestAccept

	// ContextKeyResponseHeaders is populated in the context whenever a
	// ServerFinalizerFunc is specified. Its value is of type http.Header, and
	// is captured only once the entire response has been written.
	ContextKeyResponseHeaders

	// ContextKeyResponseSize is populated in the context whenever a
	// ServerFinalizerFunc is specified. Its value is of type int64.
	ContextKeyResponseSize
)

Variables

This section is empty.

Functions

func DefaultErrorEncoder

func DefaultErrorEncoder(_ context.Context, err error, w http.ResponseWriter)

DefaultErrorEncoder writes the error to the ResponseWriter, by default a content type of text/plain, a body of the plain text of the error, and a status code of 500. If the error implements Headerer, the provided headers will be applied to the response. If the error implements json.Marshaler, and the marshaling succeeds, a content type of application/json and the JSON encoded form of the error will be used. If the error implements StatusCoder, the provided StatusCode will be used instead of 500.

func EncodeJSONRequest

func EncodeJSONRequest(c context.Context, r *http.Request, request interface{}) error

EncodeJSONRequest is an EncodeRequestFunc that serializes the request as a JSON object to the Request body. Many JSON-over-HTTP services can use it as a sensible default. If the request implements Headerer, the provided headers will be applied to the request.

func EncodeJSONResponse

func EncodeJSONResponse[Response any](_ context.Context, w http.ResponseWriter, response Response) error

EncodeJSONResponse is a EncodeResponseFunc that serializes the response as a JSON object to the ResponseWriter. Many JSON-over-HTTP services can use it as a sensible default. If the response implements Headerer, the provided headers will be applied to the response. If the response implements StatusCoder, the provided StatusCode will be used instead of 200.

func EncodeXMLRequest

func EncodeXMLRequest(c context.Context, r *http.Request, request interface{}) error

EncodeXMLRequest is an EncodeRequestFunc that serializes the request as a XML object to the Request body. If the request implements Headerer, the provided headers will be applied to the request.

func NopRequestDecoder

func NopRequestDecoder(ctx context.Context, r *http.Request) (interface{}, error)

NopRequestDecoder is a DecodeRequestFunc that can be used for requests that do not need to be decoded, and simply returns nil, nil.

func PopulateRequestContext

func PopulateRequestContext(ctx context.Context, r *http.Request) context.Context

PopulateRequestContext is a RequestFunc that populates several values into the context from the HTTP request. Those values may be extracted using the corresponding ContextKey type in this package.

Example
handler := NewServer(
	func(ctx context.Context, request interface{}) (response interface{}, err error) {
		fmt.Println("Method", ctx.Value(ContextKeyRequestMethod).(string))
		fmt.Println("RequestPath", ctx.Value(ContextKeyRequestPath).(string))
		fmt.Println("RequestURI", ctx.Value(ContextKeyRequestURI).(string))
		fmt.Println("X-Request-ID", ctx.Value(ContextKeyRequestXRequestID).(string))
		return struct{}{}, nil
	},
	func(context.Context, *http.Request) (interface{}, error) { return struct{}{}, nil },
	func(context.Context, http.ResponseWriter, interface{}) error { return nil },
	ServerBefore[interface{}, interface{}](PopulateRequestContext),
)

server := httptest.NewServer(handler)
defer server.Close()

req, _ := http.NewRequest("PATCH", fmt.Sprintf("%s/search?q=sympatico", server.URL), nil)
req.Header.Set("X-Request-Id", "a1b2c3d4e5")
http.DefaultClient.Do(req)
Output:

Method PATCH
RequestPath /search
RequestURI /search?q=sympatico
X-Request-ID a1b2c3d4e5

Types

type Client

type Client[Request, Response any] struct {
	// contains filtered or unexported fields
}

Client wraps a URL and provides a method that implements endpoint.Endpoint.

func NewClient

func NewClient[Request, Response any](method string, tgt *url.URL, enc EncodeRequestFunc[Request], dec DecodeResponseFunc[Response], options ...ClientOption[Request, Response]) *Client[Request, Response]

NewClient constructs a usable Client for a single remote method.

func NewExplicitClient

func NewExplicitClient[Request, Response any](req CreateRequestFunc[Request], dec DecodeResponseFunc[Response], options ...ClientOption[Request, Response]) *Client[Request, Response]

NewExplicitClient is like NewClient but uses a CreateRequestFunc instead of a method, target URL, and EncodeRequestFunc, which allows for more control over the outgoing HTTP request.

func (Client[Request, Response]) Endpoint

func (c Client[Request, Response]) Endpoint() endpoint.Endpoint[Request, Response]

Endpoint returns a usable Go kit endpoint that calls the remote HTTP endpoint.

type ClientFinalizerFunc

type ClientFinalizerFunc func(ctx context.Context, err error)

ClientFinalizerFunc can be used to perform work at the end of a client HTTP request, after the response is returned. The principal intended use is for error logging. Additional response parameters are provided in the context under keys with the ContextKeyResponse prefix. Note: err may be nil. There maybe also no additional response parameters depending on when an error occurs.

type ClientOption

type ClientOption[Request, Response any] func(*Client[Request, Response])

ClientOption sets an optional parameter for clients.

func BufferedStream

func BufferedStream[Request, Response any](buffered bool) ClientOption[Request, Response]

BufferedStream sets whether the HTTP response body is left open, allowing it to be read from later. Useful for transporting a file as a buffered stream. That body has to be drained and closed to properly end the request.

func ClientAfter

func ClientAfter[Request, Response any](after ...ClientResponseFunc) ClientOption[Request, Response]

ClientAfter adds one or more ClientResponseFuncs, which are applied to the incoming HTTP response prior to it being decoded. This is useful for obtaining anything off of the response and adding it into the context prior to decoding.

func ClientBefore

func ClientBefore[Request, Response any](before ...RequestFunc) ClientOption[Request, Response]

ClientBefore adds one or more RequestFuncs to be applied to the outgoing HTTP request before it's invoked.

func ClientFinalizer

func ClientFinalizer[Request, Response any](f ...ClientFinalizerFunc) ClientOption[Request, Response]

ClientFinalizer adds one or more ClientFinalizerFuncs to be executed at the end of every HTTP request. Finalizers are executed in the order in which they were added. By default, no finalizer is registered.

func SetClient

func SetClient[Request, Response any](client HTTPClient) ClientOption[Request, Response]

SetClient sets the underlying HTTP client used for requests. By default, http.DefaultClient is used.

type ClientResponseFunc

type ClientResponseFunc func(context.Context, *http.Response) context.Context

ClientResponseFunc may take information from an HTTP request and make the response available for consumption. ClientResponseFuncs are only executed in clients, after a request has been made, but prior to it being decoded.

type CreateRequestFunc

type CreateRequestFunc[Request any] func(context.Context, Request) (*http.Request, error)

CreateRequestFunc creates an outgoing HTTP request based on the passed request object. It's designed to be used in HTTP clients, for client-side endpoints. It's a more powerful version of EncodeRequestFunc, and can be used if more fine-grained control of the HTTP request is required.

type DecodeRequestFunc

type DecodeRequestFunc[Request any] func(context.Context, *http.Request) (request Request, err error)

DecodeRequestFunc extracts a user-domain request object from an HTTP request object. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward DecodeRequestFunc could be something that JSON decodes from the request body to the concrete request type.

type DecodeResponseFunc

type DecodeResponseFunc[Response any] func(context.Context, *http.Response) (response Response, err error)

DecodeResponseFunc extracts a user-domain response object from an HTTP response object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward DecodeResponseFunc could be something that JSON decodes from the response body to the concrete response type.

type EncodeRequestFunc

type EncodeRequestFunc[Request any] func(context.Context, *http.Request, Request) error

EncodeRequestFunc encodes the passed request object into the HTTP request object. It's designed to be used in HTTP clients, for client-side endpoints. One straightforward EncodeRequestFunc could be something that JSON encodes the object directly to the request body.

type EncodeResponseFunc

type EncodeResponseFunc[Response any] func(context.Context, http.ResponseWriter, Response) error

EncodeResponseFunc encodes the passed response object to the HTTP response writer. It's designed to be used in HTTP servers, for server-side endpoints. One straightforward EncodeResponseFunc could be something that JSON encodes the object directly to the response body.

type ErrorEncoder

type ErrorEncoder func(ctx context.Context, err error, w http.ResponseWriter)

ErrorEncoder is responsible for encoding an error to the ResponseWriter. Users are encouraged to use custom ErrorEncoders to encode HTTP errors to their clients, and will likely want to pass and check for their own error types. See the example shipping/handling service.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is an interface that models *http.Client.

type Headerer

type Headerer interface {
	Headers() http.Header
}

Headerer is checked by DefaultErrorEncoder. If an error value implements Headerer, the provided headers will be applied to the response writer, after the Content-Type is set.

type RequestFunc

type RequestFunc func(context.Context, *http.Request) context.Context

RequestFunc may take information from an HTTP request and put it into a request context. In Servers, RequestFuncs are executed prior to invoking the endpoint. In Clients, RequestFuncs are executed after creating the request but prior to invoking the HTTP client.

func SetRequestHeader

func SetRequestHeader(key, val string) RequestFunc

SetRequestHeader returns a RequestFunc that sets the given header.

type Server

type Server[Request, Response any] struct {
	// contains filtered or unexported fields
}

Server wraps an endpoint and implements http.Handler.

func NewServer

func NewServer[Request, Response any](
	e endpoint.Endpoint[Request, Response],
	dec DecodeRequestFunc[Request],
	enc EncodeResponseFunc[Response],
	options ...ServerOption[Request, Response],
) *Server[Request, Response]

NewServer constructs a new server, which implements http.Handler and wraps the provided endpoint.

func (Server[Request, Response]) ServeHTTP

func (s Server[Request, Response]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

type ServerFinalizerFunc

type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request)

ServerFinalizerFunc can be used to perform work at the end of an HTTP request, after the response has been written to the client. The principal intended use is for request logging. In addition to the response code provided in the function signature, additional response parameters are provided in the context under keys with the ContextKeyResponse prefix.

type ServerOption

type ServerOption[Request, Response any] func(*Server[Request, Response])

ServerOption sets an optional parameter for servers.

func ServerAfter

func ServerAfter[Request, Response any](after ...ServerResponseFunc) ServerOption[Request, Response]

ServerAfter functions are executed on the HTTP response writer after the endpoint is invoked, but before anything is written to the client.

func ServerBefore

func ServerBefore[Request, Response any](before ...RequestFunc) ServerOption[Request, Response]

ServerBefore functions are executed on the HTTP request object before the request is decoded.

func ServerErrorEncoder

func ServerErrorEncoder[Request, Response any](ee ErrorEncoder) ServerOption[Request, Response]

ServerErrorEncoder is used to encode errors to the http.ResponseWriter whenever they're encountered in the processing of a request. Clients can use this to provide custom error formatting and response codes. By default, errors will be written with the DefaultErrorEncoder.

func ServerErrorHandler

func ServerErrorHandler[Request, Response any](errorHandler transport.ErrorHandler) ServerOption[Request, Response]

ServerErrorHandler is used to handle non-terminal errors. By default, non-terminal errors are ignored. This is intended as a diagnostic measure. Finer-grained control of error handling, including logging in more detail, should be performed in a custom ServerErrorEncoder or ServerFinalizer, both of which have access to the context.

func ServerErrorLogger

func ServerErrorLogger[Request, Response any](logger log.Logger) ServerOption[Request, Response]

ServerErrorLogger is used to log non-terminal errors. By default, no errors are logged. This is intended as a diagnostic measure. Finer-grained control of error handling, including logging in more detail, should be performed in a custom ServerErrorEncoder or ServerFinalizer, both of which have access to the context. Deprecated: Use ServerErrorHandler instead.

func ServerFinalizer

func ServerFinalizer[Request, Response any](f ...ServerFinalizerFunc) ServerOption[Request, Response]

ServerFinalizer is executed at the end of every HTTP request. By default, no finalizer is registered.

type ServerResponseFunc

type ServerResponseFunc func(context.Context, http.ResponseWriter) context.Context

ServerResponseFunc may take information from a request context and use it to manipulate a ResponseWriter. ServerResponseFuncs are only executed in servers, after invoking the endpoint but prior to writing a response.

func SetContentType

func SetContentType(contentType string) ServerResponseFunc

SetContentType returns a ServerResponseFunc that sets the Content-Type header to the provided value.

func SetResponseHeader

func SetResponseHeader(key, val string) ServerResponseFunc

SetResponseHeader returns a ServerResponseFunc that sets the given header.

type StatusCoder

type StatusCoder interface {
	StatusCode() int
}

StatusCoder is checked by DefaultErrorEncoder. If an error value implements StatusCoder, the StatusCode will be used when encoding the error. By default, StatusInternalServerError (500) is used.

Directories

Path Synopsis
Package jsonrpc provides a JSON RPC (v2.0) binding for endpoints.
Package jsonrpc provides a JSON RPC (v2.0) binding for endpoints.

Jump to

Keyboard shortcuts

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