http

package
v2.1.1-0...-182a82a Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2021 License: MIT Imports: 29 Imported by: 0

README

HTTP

Provides HTTP client and server implementations.

endpoint "mock" "http" {
	endpoint = "/"
	method = "GET"
	codec = "json"
	read_timeout = "5s"
	write_timeout = "5s"
}

Services could be defined inside the HCL definitions.

service "mock" "http" {
	host = "https://service.prod.svc.cluster.local"

	options {
		flush_interval = "1s"
		timeout = "60s"
		keep_alive = "60s"
		max_idle_conns = "100"
	}
}

Or in schema definitions such as proto.

rpc Mock(Empty) returns (Empty) {
	option (semaphore.http) = {
		endpoint: "/endpoint"
		method: "GET"
	};
};

Object properties available inside the request object could be referenced inside a endpoint.

rpc Mock(Empty) returns (Empty) {
	option (semaphore.http) = {
		endpoint: "/endpoint/:id"
		method: "GET"
	};
};

Override services options through a select.

services {
    select "proto.users.*" {
			host = "api.jexia.com"
			insecure = "false"
			ca_file = "/etc/ca.crt"
    }

    select "proto.projects.*" {
      host = "api.jexia.com"
			insecure = "true"
    }
}

Documentation

Index

Constants

View Source
const (
	// InsecureOption connection flag
	InsecureOption = "insecure"
	// CAFileOption certificate authority file path
	CAFileOption = "ca_file"
	// ReadTimeoutOption represents the HTTP read timeout option key
	ReadTimeoutOption = "read_timeout"
	// WriteTimeoutOption represents the HTTP write timeout option key
	WriteTimeoutOption = "write_timeout"
	// EndpointOption represents the HTTP endpoints option key
	EndpointOption = "endpoint"
	// MethodOption represents the HTTP method option key
	MethodOption = "method"
	// CodecOption represents the HTTP listener codec option key
	CodecOption = "codec"
	// RequestCodecOption represents the HTTP listener request codec option key
	RequestCodecOption = "request_codec"
	// ResponseCodecOption represents the HTTP listener response codec option key
	ResponseCodecOption = "response_codec"
	// FlushIntervalOption represents the flush interval option key
	FlushIntervalOption = "flush_interval"
	// TimeoutOption represents the timeout option key
	TimeoutOption = "timeout"
	// KeepAliveOption represents the keep alive option key
	KeepAliveOption = "keep_alive"
	// MaxIdleConnsOption represents the max idle connections option key
	MaxIdleConnsOption = "max_idle_conns"
)
View Source
const AcceptHeaderKey = "Accept"

AcceptHeaderKey represents the HTTP header accept key

View Source
const ContentTypeHeaderKey = "Content-Type"

ContentTypeHeaderKey represents the HTTP header content type key

Variables

View Source
var ContentTypes = map[string]string{
	"json":            string(ApplicationJSON),
	"form-urlencoded": string(ApplicationWWWFormURLEncoded),
	"proto":           string(ApplicationProtobuf),
}

ContentTypes represents a lists of available codec content types and their Content-Type value

Functions

func AppendHTTPHeader

func AppendHTTPHeader(dest metadata.MD, src http.Header)

AppendHTTPHeader appends the given HTTP header into a transport header

func CopyHTTPHeader

func CopyHTTPHeader(source http.Header) metadata.MD

CopyHTTPHeader copies the given HTTP header into a transport header

func CopyMetadataHeader

func CopyMetadataHeader(header metadata.MD) http.Header

CopyMetadataHeader copies the given transport header into a HTTP header

func GetMethodEndpoint

func GetMethodEndpoint(method *specs.Method) (string, string, error)

GetMethodEndpoint attempts to find the endpoint for the given method. Empty values are returned when a empty method name is given.

func LookupEndpointReferences

func LookupEndpointReferences(method *Method, store references.Store) string

LookupEndpointReferences looks up the references within the given endpoint and returns the newly constructed endpoint

func NamedParameters

func NamedParameters(url string) []string

NamedParameters returns the available named parameters inside the given url

func NewCaller

func NewCaller() transport.NewCaller

NewCaller constructs a new HTTP caller

func NewListener

func NewListener(addr string, options ...ListenerOption) transport.NewListener

NewListener constructs a new listener for the given addr

func NewProxy

func NewProxy(options *CallerOptions) *httputil.ReverseProxy

NewProxy constructs a new reverse proxy with the given options

func NewRequest

func NewRequest(req *http.Request) *transport.Request

NewRequest constructs a new transport request of the given http request

func OptionsHandler

func OptionsHandler(origins, headers, methods []string) http.Handler

OptionsHandler creates a global handler for OPTIONS requests.

func RawNamedParameters

func RawNamedParameters(url string) []string

RawNamedParameters returns the available named parameters including the selector

func SetHTTPHeader

func SetHTTPHeader(writer http.Header, metadata metadata.MD)

SetHTTPHeader copies the given transport header into a HTTP header

func TemplateReferences

func TemplateReferences(value string, functions functions.Custom) ([]*specs.Property, error)

TemplateReferences returns the property references within the given value

Types

type Call

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

Call represents the HTTP caller implementation

func (*Call) Address

func (call *Call) Address() string

func (*Call) Close

func (call *Call) Close() error

Close closes the given caller

func (*Call) GetMethod

func (call *Call) GetMethod(name string) transport.Method

GetMethod attempts to return a method matching the given name

func (*Call) GetMethods

func (call *Call) GetMethods() []transport.Method

GetMethods returns the available methods within the HTTP caller

func (*Call) SendMsg

func (call *Call) SendMsg(ctx context.Context, rw transport.ResponseWriter, pr *transport.Request, refs references.Store) error

SendMsg calls the configured host and attempts to call the given endpoint with the given headers and stream

type Caller

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

Caller represents the caller constructor

func (*Caller) Dial

func (caller *Caller) Dial(service *specs.Service, functions functions.Custom, opts specs.Options, resolver discovery.Resolver) (transport.Call, error)

Dial constructs a new caller for the given host

func (*Caller) Name

func (caller *Caller) Name() string

Name returns the name of the given caller

type CallerOptions

type CallerOptions struct {
	Timeout       time.Duration
	KeepAlive     time.Duration
	FlushInterval time.Duration
	MaxIdleConns  int
	Insecure      bool
	CAFile        string
}

CallerOptions represents the available HTTP options

func ParseCallerOptions

func ParseCallerOptions(options specs.Options) (*CallerOptions, error)

ParseCallerOptions parses the given specs options into HTTP options

type ContentType

type ContentType string

ContentType represents a supported content type

const (
	ApplicationJSON              ContentType = "application/json"
	ApplicationWWWFormURLEncoded ContentType = "application/x-www-form-urlencoded"
	ApplicationProtobuf          ContentType = "application/protobuf"
)

Available content types

type EndpointOptions

type EndpointOptions struct {
	Method        string
	Endpoint      string
	ReadTimeout   time.Duration
	WriteTimeout  time.Duration
	RequestCodec  string
	ResponseCodec string
}

EndpointOptions represents the available HTTP options

func ParseEndpointOptions

func ParseEndpointOptions(options specs.Options) (*EndpointOptions, error)

ParseEndpointOptions parses the given specs options into HTTP options

type ErrInvalidHost

type ErrInvalidHost struct {
	Host string
	// contains filtered or unexported fields
}

ErrInvalidHost occurs when provided host is invalid

func (ErrInvalidHost) Error

func (e ErrInvalidHost) Error() string

Error returns a description of the given error as a string

func (ErrInvalidHost) Prettify

func (e ErrInvalidHost) Prettify() prettyerr.Error

Prettify returns the prettified version of the given error

func (ErrInvalidHost) Unwrap

func (i ErrInvalidHost) Unwrap() error

type ErrRouteConflict

type ErrRouteConflict string

ErrRouteConflict is returned when HTTP route conflict is detected.

func (ErrRouteConflict) Error

func (e ErrRouteConflict) Error() string

type ErrUndefinedCodec

type ErrUndefinedCodec struct {
	Codec string
}

ErrUndefinedCodec occurs when undefined codec is called

func (ErrUndefinedCodec) Error

func (e ErrUndefinedCodec) Error() string

Error returns a description of the given error as a string

func (ErrUndefinedCodec) Prettify

func (e ErrUndefinedCodec) Prettify() prettyerr.Error

Prettify returns the prettified version of the given error

type ErrUnknownMethod

type ErrUnknownMethod struct {
	Method  string
	Service string
}

ErrUnknownMethod occurs when undefined method is called

func (ErrUnknownMethod) Error

func (e ErrUnknownMethod) Error() string

Error returns a description of the given error as a string

func (ErrUnknownMethod) Prettify

func (e ErrUnknownMethod) Prettify() prettyerr.Error

Prettify returns the prettified version of the given error

type Handle

type Handle struct {
	*transport.Endpoint

	Options *EndpointOptions
	Proxy   *Proxy
	// contains filtered or unexported fields
}

Handle holds a endpoint its options and a optional request and response

func NewHandle

func NewHandle(ctx *broker.Context, endpoint *transport.Endpoint, options *EndpointOptions, constructors map[string]codec.Constructor) (*Handle, error)

NewHandle constructs a new handle function for the given endpoint to the given flow

func (*Handle) HTTPFunc

func (handle *Handle) HTTPFunc(w http.ResponseWriter, r *http.Request, ps httprouter.Params)

HTTPFunc represents a HTTP function which could be used inside a HTTP router

type Listener

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

Listener represents a HTTP listener

func (*Listener) Close

func (listener *Listener) Close() error

Close closes the given listener

func (*Listener) Handle

func (listener *Listener) Handle(ctx *broker.Context, endpoints []*transport.Endpoint, codecs map[string]codec.Constructor) error

Handle parses the given endpoints and constructs route handlers

func (*Listener) Name

func (listener *Listener) Name() string

Name returns the name of the given listener

func (*Listener) Serve

func (listener *Listener) Serve() (err error)

Serve opens the HTTP listener and calls the given handler function on reach request

type ListenerOption

type ListenerOption func(*ListenerOptions) error

ListenerOption defines a single listener option

func WithCertFile

func WithCertFile(path string) ListenerOption

WithCertFile defines certificate file

func WithKeyFile

func WithKeyFile(path string) ListenerOption

WithKeyFile defines key file

func WithOrigins

func WithOrigins(list []string) ListenerOption

WithOrigins sets allowed origins for incoming preflight requests

func WithReadTimeout

func WithReadTimeout(timeout string) ListenerOption

WithReadTimeout overrides the default read timeout

func WithWriteTimeout

func WithWriteTimeout(timeout string) ListenerOption

WithWriteTimeout overrides default write timeout

type ListenerOptions

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

ListenerOptions represents the available HTTP options

func DefaultListenerOptions

func DefaultListenerOptions() *ListenerOptions

DefaultListenerOptions returns default listener configuration

func NewListenerOptions

func NewListenerOptions(options ...ListenerOption) (*ListenerOptions, error)

NewListenerOptions creates listener config with provided options

type Method

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

Method represents a service method

func (*Method) GetName

func (method *Method) GetName() string

GetName returns the method name

func (*Method) References

func (method *Method) References() []*specs.Property

References returns the available method references

type Proxy

type Proxy struct {
	Handle *httputil.ReverseProxy
	Header *metadata.Manager
}

Proxy represents a HTTP reverse proxy

type Request

type Request struct {
	Codec  codec.Manager
	Header *metadata.Manager
}

Request represents a codec manager and header manager

type ResponseWriter

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

A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) *ResponseWriter

NewResponseWriter constructs a new HTTP response writer of the given HTTP response writer

func (*ResponseWriter) Header

func (rw *ResponseWriter) Header() metadata.MD

Header returns the header map that will be sent by WriteHeader. The Header map also is the mechanism with which Handlers can set HTTP trailers.

func (*ResponseWriter) Write

func (rw *ResponseWriter) Write(bb []byte) (int, error)

Write writes the data to the connection as part of an HTTP reply.

func (*ResponseWriter) WriteHeader

func (rw *ResponseWriter) WriteHeader(status int)

WriteHeader sends an HTTP response header with the provided status code.

type UniqueStringItems

type UniqueStringItems map[string]struct{}

UniqueStringItems collects strings to be returned as a list of unique items. Note that it is not suitable for concurrent usage and does not guartantee the order of items.

func (UniqueStringItems) Add

func (usi UniqueStringItems) Add(item string)

Add item to the list.

func (UniqueStringItems) Get

func (usi UniqueStringItems) Get() []string

Get the list of unique items.

Jump to

Keyboard shortcuts

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