http

package
v2.14.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2023 License: Apache-2.0 Imports: 25 Imported by: 182

Documentation

Overview

Package http implements an HTTP binding using net/http module

Index

Constants

View Source
const (
	DefaultAllowedRate = 1000
	DefaultTimeout     = time.Second * 600
)
View Source
const ContentLength = "Content-Length"
View Source
const ContentType = "Content-Type"
View Source
const (
	// DefaultShutdownTimeout defines the default timeout given to the http.Server when calling Shutdown.
	DefaultShutdownTimeout = time.Minute * 1
)

Variables

View Source
var NewObserved = New

NewObserved creates an HTTP protocol with trace propagating middleware. Deprecated: now this behaves like New and it will be removed in future releases, setup the http observed protocol using the opencensus separate module NewObservedHttp

Functions

func HeaderFrom added in v2.4.0

func HeaderFrom(ctx context.Context) http.Header

func IsHTTPBatch added in v2.14.0

func IsHTTPBatch(header nethttp.Header) bool

IsHTTPBatch returns if the current http.Request or http.Response is a batch event operation, by checking the header `Content-Type` value.

func NewEventFromHTTPRequest added in v2.12.0

func NewEventFromHTTPRequest(req *nethttp.Request) (*event.Event, error)

NewEventFromHTTPRequest returns an Event.

func NewEventFromHTTPResponse added in v2.12.0

func NewEventFromHTTPResponse(resp *nethttp.Response) (*event.Event, error)

NewEventFromHTTPResponse returns an Event.

func NewEventsFromHTTPRequest added in v2.14.0

func NewEventsFromHTTPRequest(req *nethttp.Request) ([]event.Event, error)

NewEventsFromHTTPRequest returns a batched set of Events from a HTTP Request

func NewEventsFromHTTPResponse added in v2.14.0

func NewEventsFromHTTPResponse(resp *nethttp.Response) ([]event.Event, error)

NewEventsFromHTTPResponse returns a batched set of Events from a HTTP Response

func NewHTTPRequestFromEvent added in v2.14.0

func NewHTTPRequestFromEvent(ctx context.Context, url string, event event.Event) (*nethttp.Request, error)

NewHTTPRequestFromEvent creates a http.Request object that can be used with any http.Client for a singular event. This is an HTTP POST action to the provided url.

func NewHTTPRequestFromEvents added in v2.14.0

func NewHTTPRequestFromEvents(ctx context.Context, url string, events []event.Event) (*nethttp.Request, error)

NewHTTPRequestFromEvents creates a http.Request object that can be used with any http.Client for sending a batched set of events. This is an HTTP POST action to the provided url.

func NewResult

func NewResult(statusCode int, messageFmt string, args ...interface{}) protocol.Result

NewResult returns a fully populated http Result that should be used as a transport.Result.

func NewRetriesResult

func NewRetriesResult(result protocol.Result, retries int, startTime time.Time, attempts []protocol.Result) protocol.Result

NewRetriesResult returns a http RetriesResult that should be used as a transport.Result without retries

func WithCustomHeader added in v2.4.0

func WithCustomHeader(ctx context.Context, header http.Header) context.Context

func WithRequestDataAtContext added in v2.7.0

func WithRequestDataAtContext(ctx context.Context, r *nethttp.Request) context.Context

WithRequestDataAtContext uses the http.Request to add RequestData

information to the Context.

func WriteRequest

func WriteRequest(ctx context.Context, m binding.Message, httpRequest *http.Request, transformers ...binding.Transformer) error

WriteRequest fills the provided httpRequest with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).

func WriteResponseWriter

func WriteResponseWriter(ctx context.Context, m binding.Message, status int, rw http.ResponseWriter, transformers ...binding.Transformer) error

WriteResponseWriter writes out to the the provided httpResponseWriter with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).

Types

type IsRetriable added in v2.4.0

type IsRetriable func(statusCode int) bool

IsRetriable is a custom function that can be used to override the default retriable status codes.

type Message

type Message struct {
	Header     nethttp.Header
	BodyReader io.ReadCloser
	OnFinish   func(error) error
	// contains filtered or unexported fields
}

Message holds the Header and Body of a HTTP Request or Response. The Message instance *must* be constructed from NewMessage function. This message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods

func NewMessage

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

NewMessage returns a binding.Message with header and data. The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods

func NewMessageFromHttpRequest

func NewMessageFromHttpRequest(req *nethttp.Request) *Message

NewMessageFromHttpRequest returns a binding.Message with header and data. The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods

func NewMessageFromHttpResponse

func NewMessageFromHttpResponse(resp *nethttp.Response) *Message

NewMessageFromHttpResponse returns a binding.Message with header and data. The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods

func (*Message) Context added in v2.4.0

func (m *Message) Context() context.Context

func (*Message) Finish

func (m *Message) Finish(err error) error

func (*Message) GetAttribute

func (m *Message) GetAttribute(k spec.Kind) (spec.Attribute, interface{})

func (*Message) GetExtension

func (m *Message) GetExtension(name string) interface{}

func (*Message) ReadBinary

func (m *Message) ReadBinary(ctx context.Context, encoder binding.BinaryWriter) (err error)

func (*Message) ReadEncoding

func (m *Message) ReadEncoding() binding.Encoding

func (*Message) ReadStructured

func (m *Message) ReadStructured(ctx context.Context, encoder binding.StructuredWriter) error

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(*Protocol) error

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

func WithClient

func WithClient(client nethttp.Client) Option

WithClient sets the protocol client

func WithDefaultOptionsHandlerFunc

func WithDefaultOptionsHandlerFunc(methods []string, rate int, origins []string, callback bool) Option

WithDefaultOptionsHandlerFunc sets the options handler to be the built in handler and configures the options. methods: the supported methods reported to OPTIONS caller. rate: the rate limit reported to OPTIONS caller. origins: the prefix of the accepted origins, or "*". callback: preform the callback to ACK the OPTIONS request.

func WithGetHandlerFunc

func WithGetHandlerFunc(fn nethttp.HandlerFunc) Option

WithGetHandlerFunc sets the http GET handler func

func WithHeader

func WithHeader(key, value string) Option

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

func WithIsRetriableFunc added in v2.4.0

func WithIsRetriableFunc(isRetriable IsRetriable) Option

WithIsRetriableFunc sets the function that gets called to determine if an error should be retried. If not set, the defaultIsRetriableFunc is used.

func WithListener

func WithListener(l net.Listener) Option

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

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 WithOptionsHandlerFunc

func WithOptionsHandlerFunc(fn nethttp.HandlerFunc) Option

WithOptionsHandlerFunc sets the http OPTIONS handler func

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 WithRateLimiter added in v2.7.0

func WithRateLimiter(rl RateLimiter) Option

func WithRequestDataAtContextMiddleware added in v2.7.0

func WithRequestDataAtContextMiddleware() Option

WithRequestDataAtContextMiddleware adds to the Context RequestData. This enables a user's dispatch handler to inspect HTTP request information by retrieving it from the Context.

func WithRoundTripper

func WithRoundTripper(roundTripper nethttp.RoundTripper) Option

WithRoundTripper sets the HTTP RoundTripper.

func WithRoundTripperDecorator added in v2.4.0

func WithRoundTripperDecorator(decorator func(roundTripper nethttp.RoundTripper) nethttp.RoundTripper) Option

WithRoundTripperDecorator decorates the default HTTP RoundTripper chosen.

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

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

func WithTarget

func WithTarget(targetUrl string) Option

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

type Protocol

type Protocol struct {
	Target          *url.URL
	RequestTemplate *http.Request
	Client          *http.Client

	// OptionsHandlerFn handles the OPTIONS method requests and is intended to
	// implement the abuse protection spec:
	// https://github.com/cloudevents/spec/blob/v1.0/http-webhook.md#4-abuse-protection
	OptionsHandlerFn http.HandlerFunc
	WebhookConfig    *WebhookConfig

	GetHandlerFn    http.HandlerFunc
	DeleteHandlerFn http.HandlerFunc

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

	// Port is the port configured to bind the receiver to. Defaults to 8080.
	// If you want to know the effective port you're listening to, use GetListeningPort()
	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 Protocol will create a one.
	Handler *http.ServeMux
	// contains filtered or unexported fields
}

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

func New

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

func (*Protocol) GetListeningPort

func (p *Protocol) GetListeningPort() int

GetListeningPort returns the listening port. Returns -1 if it's not listening.

func (*Protocol) GetPath

func (p *Protocol) 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 (*Protocol) OpenInbound

func (p *Protocol) OpenInbound(ctx context.Context) error

func (*Protocol) OptionsHandler

func (p *Protocol) OptionsHandler(rw http.ResponseWriter, req *http.Request)

func (*Protocol) Receive

func (p *Protocol) Receive(ctx context.Context) (binding.Message, error)

Receive the next incoming HTTP request as a CloudEvent. Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent Returns io.EOF if the receiver is closed.

func (*Protocol) Request

func (p *Protocol) Request(ctx context.Context, m binding.Message, transformers ...binding.Transformer) (binding.Message, error)

Request implements binding.Requester

func (*Protocol) Respond

Respond receives the next incoming HTTP request as a CloudEvent and waits for the response callback to invoked before continuing. Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent Returns io.EOF if the receiver is closed.

func (*Protocol) Send

func (p *Protocol) Send(ctx context.Context, m binding.Message, transformers ...binding.Transformer) error

Send implements binding.Sender

func (*Protocol) ServeHTTP

func (p *Protocol) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler. Blocks until ResponseFn is invoked.

func (*Protocol) ValidateOrigin

func (p *Protocol) ValidateOrigin(req *http.Request) (string, bool)

func (*Protocol) ValidateRequestOrigin

func (p *Protocol) ValidateRequestOrigin(req *http.Request) (string, bool)

type RateLimiter added in v2.7.0

type RateLimiter interface {
	// Allow attempts to take one token from the rate limiter for the specified
	// request. It returns ok when this operation was successful. In case ok is
	// false, reset will indicate the time in seconds when it is safe to perform
	// another attempt. An error is returned when this operation failed, e.g. due to
	// a backend error.
	Allow(ctx context.Context, r *http.Request) (ok bool, reset uint64, err error)
	// Close terminates rate limiter and cleans up any data structures or
	// connections that may remain open. After a store is stopped, Take() should
	// always return zero values.
	Close(ctx context.Context) error
}

type RequestData added in v2.7.0

type RequestData struct {
	URL        *url.URL
	Header     nethttp.Header
	RemoteAddr string
	Host       string
}

RequestData holds the http.Request information subset that can be used to retrieve HTTP information for an incoming CloudEvent.

func RequestDataFromContext added in v2.7.0

func RequestDataFromContext(ctx context.Context) *RequestData

RequestDataFromContext retrieves RequestData from the Context. If not set nil is returned.

type Result

type Result struct {
	StatusCode int
	Format     string
	Args       []interface{}
}

Result wraps the fields required to make adjustments for http Responses.

func (*Result) Error

func (e *Result) Error() string

Error returns the string that is formed by using the format string with the provided args.

func (*Result) Is

func (e *Result) Is(target error) bool

Is returns if the target error is a Result type checking target.

type RetriesResult

type RetriesResult struct {
	// The last result
	protocol.Result

	// Retries is the number of times the request was tried
	Retries int

	// Duration records the time spent retrying. Exclude the successful request (if any)
	Duration time.Duration

	// Attempts of all failed requests. Exclude last result.
	Attempts []protocol.Result
}

RetriesResult wraps the fields required to make adjustments for http Responses.

func (*RetriesResult) Error

func (e *RetriesResult) Error() string

Error returns the string that is formed by using the format string with the provided args.

func (*RetriesResult) Is

func (e *RetriesResult) Is(target error) bool

Is returns if the target error is a RetriesResult type checking target.

type WebhookConfig

type WebhookConfig struct {
	AllowedMethods  []string // defaults to POST
	AllowedRate     *int
	AutoACKCallback bool
	AllowedOrigins  []string
}

Jump to

Keyboard shortcuts

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