http

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2020 License: Apache-2.0 Imports: 25 Imported by: 64

Documentation

Overview

Package http implements the CloudEvent transport implementation using HTTP.

Index

Constants

View Source
const (
	// DefaultShutdownTimeout defines the default timeout given to the http.Server when calling Shutdown.
	DefaultShutdownTimeout = time.Minute * 1

	// TransportName is the name of this transport.
	TransportName = "HTTP"
)

Variables

View Source
var (
	// LatencyMs measures the latency in milliseconds for the http transport
	// methods for CloudEvents.
	LatencyMs = stats.Float64(
		"cloudevents.io/sdk-go/transport/http/latency",
		"The latency in milliseconds for the http transport methods for CloudEvents.",
		"ms")
)
View Source
var (
	// LatencyView is an OpenCensus view that shows http transport method latency.
	LatencyView = &view.View{
		Name:        "transport/http/latency",
		Measure:     LatencyMs,
		Description: "The distribution of latency inside of http transport for CloudEvents.",
		Aggregation: view.Distribution(0, .01, .1, 1, 10, 100, 1000, 10000),
		TagKeys:     observability.LatencyTags(),
	}
)

Functions

func ContextWithHeader

func ContextWithHeader(ctx context.Context, key, value string) context.Context

ContextWithHeader returns a context with a header added to the given context. Can be called multiple times to set multiple header key/value pairs.

func ContextWithLongPollTarget

func ContextWithLongPollTarget(ctx context.Context, target string) context.Context

WithLongPollTarget returns a new context with the given long poll target. `target` should be a full URL and will be injected into the long polling http request within StartReceiver.

func HeaderFrom

func HeaderFrom(ctx context.Context) http.Header

HeaderFrom extracts the header object in the given context. Always returns a non-nil Header.

func LongPollTargetFrom

func LongPollTargetFrom(ctx context.Context) *url.URL

LongPollTargetFrom looks in the given context and returns `target` as a parsed url if found and valid, otherwise nil.

func SetContextHeaders added in v1.1.0

func SetContextHeaders(ctx context.Context, headers http.Header) context.Context

SetContextHeader sets the context's headers replacing any headers currently in context.

func WithTransportContext

func WithTransportContext(ctx context.Context, tcxt TransportContext) context.Context

WithTransportContext return a context with the given TransportContext into the provided context object.

Types

type Codec

type Codec struct {
	// Encoding is the setting to inform the DefaultEncodingSelectionFn for
	// selecting a codec.
	Encoding Encoding

	// DefaultEncodingSelectionFn allows for encoding selection strategies to be injected.
	DefaultEncodingSelectionFn EncodingSelector
	// contains filtered or unexported fields
}

Codec is the wrapper for all versions of codecs supported by the http transport.

func (*Codec) Decode

func (c *Codec) Decode(ctx context.Context, msg transport.Message) (*cloudevents.Event, error)

Decode converts a provided transport message into an Event, or error.

func (*Codec) Encode

Encode encodes the provided event into a transport message.

type CodecObserved

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

CodecObserved is a wrapper to append version to observed.

func (CodecObserved) LatencyMs

func (c CodecObserved) LatencyMs() *stats.Float64Measure

LatencyMs implements Observable.LatencyMs

func (CodecObserved) MethodName

func (c CodecObserved) MethodName() string

MethodName implements Observable.MethodName

type CodecStructured

type CodecStructured struct {
	DefaultEncoding Encoding
}

CodecStructured represents an structured http transport codec for all versions. Intended to be used as a base class.

type CodecV01

type CodecV01 struct {
	CodecStructured

	DefaultEncoding Encoding
}

CodecV01 represents a http transport codec that uses CloudEvents spec v0.1

func (CodecV01) Decode

Decode implements Codec.Decode

func (CodecV01) Encode

Encode implements Codec.Encode

type CodecV02

type CodecV02 struct {
	CodecStructured

	DefaultEncoding Encoding
}

CodecV02 represents a http transport codec that uses CloudEvents spec v0.2

func (CodecV02) Decode

Decode implements Codec.Decode

func (CodecV02) Encode

Encode implements Codec.Encode

type CodecV03

type CodecV03 struct {
	CodecStructured

	DefaultEncoding Encoding
}

CodecV03 represents a http transport codec that uses CloudEvents spec v0.3

func (CodecV03) Decode

Decode implements Codec.Decode

func (CodecV03) Encode

Encode implements Codec.Encode

type CodecV1 added in v0.10.0

type CodecV1 struct {
	CodecStructured

	DefaultEncoding Encoding
}

CodecV1 represents a http transport codec that uses CloudEvents spec v1.0

func (CodecV1) Decode added in v0.10.0

func (v CodecV1) Decode(ctx context.Context, msg transport.Message) (*cloudevents.Event, error)

Decode implements Codec.Decode

func (CodecV1) Encode added in v0.10.0

Encode implements Codec.Encode

type Encoding

type Encoding int32

Encoding to use for HTTP transport.

const (
	// Default
	Default Encoding = iota
	// BinaryV01 is Binary CloudEvents spec v0.1.
	BinaryV01
	// StructuredV01 is Structured CloudEvents spec v0.1.
	StructuredV01
	// BinaryV02 is Binary CloudEvents spec v0.2.
	BinaryV02
	// StructuredV02 is Structured CloudEvents spec v0.2.
	StructuredV02
	// BinaryV03 is Binary CloudEvents spec v0.3.
	BinaryV03
	// StructuredV03 is Structured CloudEvents spec v0.3.
	StructuredV03
	// BatchedV03 is Batched CloudEvents spec v0.3.
	BatchedV03
	// BinaryV1 is Binary CloudEvents spec v1.0.
	BinaryV1
	// StructuredV03 is Structured CloudEvents spec v1.0.
	StructuredV1
	// BatchedV1 is Batched CloudEvents spec v1.0.
	BatchedV1

	// Unknown is unknown.
	Unknown

	// Binary is used for Context Based Encoding Selections to use the
	// DefaultBinaryEncodingSelectionStrategy
	Binary = "binary"

	// Structured is used for Context Based Encoding Selections to use the
	// DefaultStructuredEncodingSelectionStrategy
	Structured = "structured"

	// Batched is used for Context Based Encoding Selections to use the
	// DefaultStructuredEncodingSelectionStrategy
	Batched = "batched"
)

func ContextBasedEncodingSelectionStrategy

func ContextBasedEncodingSelectionStrategy(ctx context.Context, e cloudevents.Event) Encoding

func DefaultBinaryEncodingSelectionStrategy

func DefaultBinaryEncodingSelectionStrategy(ctx context.Context, e cloudevents.Event) Encoding

DefaultBinaryEncodingSelectionStrategy implements a selection process for which binary encoding to use based on spec version of the event.

func DefaultStructuredEncodingSelectionStrategy

func DefaultStructuredEncodingSelectionStrategy(ctx context.Context, e cloudevents.Event) Encoding

DefaultStructuredEncodingSelectionStrategy implements a selection process for which structured encoding to use based on spec version of the event.

func (Encoding) Codec

func (e Encoding) Codec() string

Codec creates a structured string to represent the the codec version.

func (Encoding) Name added in v0.10.0

func (e Encoding) Name() string

Name creates a string to represent the the codec name.

func (Encoding) String

func (e Encoding) String() string

String pretty-prints the encoding as a string.

func (Encoding) Version

func (e Encoding) Version() string

Version pretty-prints the encoding version as a string.

type EncodingSelector

type EncodingSelector func(context.Context, cloudevents.Event) Encoding

type Message

type Message struct {
	Header http.Header
	Body   []byte
}

Message is an http transport message.

func NewMessage

func NewMessage(header http.Header, body io.ReadCloser) (*Message, error)

NewMessage creates a new message from the Header and Body of an http.Request or http.Response

func (Message) CloudEventsVersion

func (m Message) CloudEventsVersion() string

CloudEventsVersion inspects a message and tries to discover and return the CloudEvents spec version.

func (*Message) Init

func (m *Message) Init(header http.Header, body io.ReadCloser) error

Copy copies a new Body and Header into a message, replacing any previous data.

func (*Message) ToRequest

func (m *Message) ToRequest(req *http.Request)

ToRequest updates a http.Request from a Message. Replaces Body, ContentLength and Method, updates Headers. Panic if req is nil

type Middleware

type Middleware func(next nethttp.Handler) nethttp.Handler

Middleware is a function that takes an existing http.Handler and wraps it in middleware, returning the wrapped http.Handler.

type Option

type Option func(*Transport) error

Option is the function signature required to be considered an http.Option.

func WithBinaryEncoding

func WithBinaryEncoding() Option

WithBinaryEncoding sets the encoding selection strategy for default encoding selections based on Event, the encoded event will be the given version in Binary form.

func WithContextBasedEncoding

func WithContextBasedEncoding() Option

WithContextBasedEncoding sets the encoding selection strategy for default encoding selections based context and then on Event, the encoded event will be the given version in the encoding specified by the given context, or Binary if not set.

func WithDefaultEncodingSelector

func WithDefaultEncodingSelector(fn EncodingSelector) Option

WithDefaultEncodingSelector sets the encoding selection strategy for default encoding selections based on Event.

func WithEncoding

func WithEncoding(encoding Encoding) Option

WithEncoding sets the encoding for clients with HTTP transports.

func WithHTTPTransport added in v1.1.0

func WithHTTPTransport(httpTransport nethttp.RoundTripper) Option

WithHTTPTransport sets the HTTP client transport.

func WithHeader

func WithHeader(key, value string) Option

WithHeader sets an additional default outbound header for all cloudevents when using an HTTP request.

func WithListener

func WithListener(l net.Listener) Option

WithListener sets the listener for StartReceiver. Only one of WithListener or WithPort is allowed.

func WithLongPollTarget

func WithLongPollTarget(targetUrl string) Option

WithLongPollTarget sets the receivers URL to perform long polling after StartReceiver is called.

func WithMethod

func WithMethod(method string) Option

WithMethod sets the HTTP verb (GET, POST, PUT, etc.) to use when using an HTTP request.

func WithMiddleware

func WithMiddleware(middleware Middleware) Option

WithMiddleware adds an HTTP middleware to the transport. It may be specified multiple times. Middleware is applied to everything before it. For example `NewClient(WithMiddleware(foo), WithMiddleware(bar))` would result in `bar(foo(original))`.

func WithPath

func WithPath(path string) Option

WithPath sets the path to receive cloudevents on for HTTP transports.

func WithPort

func WithPort(port int) Option

WithPort sets the listening port for StartReceiver. Only one of WithListener or WithPort is allowed.

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout sets the shutdown timeout when the http server is being shutdown.

func WithStructuredEncoding

func WithStructuredEncoding() Option

WithStructuredEncoding sets the encoding selection strategy for default encoding selections based on Event, the encoded event will be the given version in Structured form.

func WithTarget

func WithTarget(targetUrl string) Option

WithTarget sets the outbound recipient of cloudevents when using an HTTP request.

type Response

type Response struct {
	StatusCode int
	Message
}

Response is an http transport response.

func NewResponse

func NewResponse(header http.Header, body io.ReadCloser, statusCode int) (*Response, error)

NewResponse creates a new response from the Header and Body of an http.Request or http.Response

func (*Response) ToResponse

func (m *Response) ToResponse(resp *http.Response)

ToResponse updates a http.Response from a Response. Replaces Body, updates Headers. Panic if resp is nil

type Transport

type Transport struct {
	// The encoding used to select the codec for outbound events.
	Encoding Encoding

	// DefaultEncodingSelectionFn allows for other encoding selection strategies to be injected.
	DefaultEncodingSelectionFn EncodingSelector

	// ShutdownTimeout defines the timeout given to the http.Server when calling Shutdown.
	// If nil, DefaultShutdownTimeout is used.
	ShutdownTimeout *time.Duration

	// Deprecated - setting http client will override use of the
	// HTTP transport set with WithHTTPTransport.
	Client *http.Client

	// Req is the base http request that is used for http.Do.
	// Only .Method, .URL, .Close, and .Header is considered.
	// If not set, Req.Method defaults to POST.
	// Req.URL or context.WithTarget(url) are required for sending.
	Req *http.Request

	// Receiver is invoked target for incoming events.
	Receiver transport.Receiver
	// Converter is invoked if the incoming transport receives an undecodable
	// message.
	Converter transport.Converter
	// Port is the port to bind the receiver to. Defaults to 8080.
	Port *int
	// Path is the path to bind the receiver to. Defaults to "/".
	Path string
	// Handler is the handler the http Server will use. Use this to reuse the
	// http server. If nil, the Transport will create a one.
	Handler *http.ServeMux

	// LongPollClient is the http client that will be used to long poll.
	// If nil and LongPollReq is set, the Transport will create a one.
	LongPollClient *http.Client
	// LongPollReq is the base http request that is used for long poll.
	// Only .Method, .URL, .Close, and .Header is considered.
	// If not set, LongPollReq.Method defaults to GET.
	// LongPollReq.URL or context.WithLongPollTarget(url) are required to long
	// poll on StartReceiver.
	LongPollReq *http.Request
	// contains filtered or unexported fields
}

Transport acts as both a http client and a http handler.

func New

func New(opts ...Option) (*Transport, error)

func (*Transport) GetPath

func (t *Transport) GetPath() string

GetPath returns the path the transport is hosted on. If the path is '/', the transport will handle requests on any URI. To discover the true path a request was received on, inspect the context from Receive(cxt, ...) with TransportContextFrom(ctx).

func (*Transport) GetPort

func (t *Transport) GetPort() int

GetPort returns the listening port. Returns -1 if there is a listening error. Note this will call net.Listen() if the listener is not already started.

func (*Transport) HasConverter

func (t *Transport) HasConverter() bool

HasConverter implements Transport.HasConverter

func (*Transport) HasTracePropagation added in v1.1.0

func (t *Transport) HasTracePropagation() bool

HasTracePropagation implements Transport.HasTracePropagation

func (*Transport) MessageToEvent

func (t *Transport) MessageToEvent(ctx context.Context, msg *Message) (*cloudevents.Event, error)

func (*Transport) Send

Send implements Transport.Send

func (*Transport) ServeHTTP

func (t *Transport) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler

func (*Transport) SetConverter

func (t *Transport) SetConverter(c transport.Converter)

SetConverter implements Transport.SetConverter

func (*Transport) SetReceiver

func (t *Transport) SetReceiver(r transport.Receiver)

SetReceiver implements Transport.SetReceiver

func (*Transport) StartReceiver

func (t *Transport) StartReceiver(ctx context.Context) error

StartReceiver implements Transport.StartReceiver NOTE: This is a blocking call.

type TransportContext

type TransportContext struct {
	URI        string
	Host       string
	Method     string
	Header     http.Header
	StatusCode int

	// IgnoreHeaderPrefixes controls what comes back from AttendToHeaders.
	// AttendToHeaders controls what is output for .String()
	IgnoreHeaderPrefixes []string
}

TransportContext allows a Receiver to understand the context of a request.

func NewTransportContext

func NewTransportContext(req *http.Request) TransportContext

NewTransportContext creates a new TransportContext from a http.Request.

func NewTransportContextFromResponse added in v0.9.0

func NewTransportContextFromResponse(res *http.Response) TransportContext

NewTransportContextFromResponse creates a new TransportContext from a http.Response. If `res` is nil, it returns a context with a http.StatusInternalServerError status code.

func TransportContextFrom

func TransportContextFrom(ctx context.Context) TransportContext

TransportContextFrom pulls a TransportContext out of a context. Always returns a non-nil object.

func (*TransportContext) AddIgnoreHeaderPrefix

func (tx *TransportContext) AddIgnoreHeaderPrefix(prefix ...string)

AddIgnoreHeaderPrefix controls what header key is to be attended to and/or printed.

func (TransportContext) AttendToHeaders

func (tx TransportContext) AttendToHeaders() []string

AttendToHeaders returns the list of headers that exist in the TransportContext that are not currently in tx.IgnoreHeaderPrefix.

func (TransportContext) String

func (tx TransportContext) String() string

String generates a pretty-printed version of the resource as a string.

type TransportResponseContext

type TransportResponseContext struct {
	// Header will be merged with the response headers.
	Header http.Header
}

TransportResponseContext allows a Receiver response with http transport specific fields.

Jump to

Keyboard shortcuts

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