runtime

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2020 License: BSD-3-Clause Imports: 35 Imported by: 17,314

Documentation

Overview

Package runtime contains runtime helper functions used by servers which protoc-gen-grpc-gateway generates.

Index

Constants

View Source
const MIMEWildcard = "*"

MIMEWildcard is the fallback MIME type used for requests which do not match a registered MIME type.

View Source
const MetadataHeaderPrefix = "Grpc-Metadata-"

MetadataHeaderPrefix is the http prefix that represents custom metadata parameters to or from a gRPC call.

View Source
const MetadataPrefix = "grpcgateway-"

MetadataPrefix is prepended to permanent HTTP header keys (as specified by the IANA) when added to the gRPC context.

View Source
const MetadataTrailerPrefix = "Grpc-Trailer-"

MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to HTTP headers in a response handled by grpc-gateway

Variables

View Source
var (
	// HTTPError replies to the request with an error.
	//
	// HTTPError is called:
	//  - From generated per-endpoint gateway handler code, when calling the backend results in an error.
	//  - From gateway runtime code, when forwarding the response message results in an error.
	//
	// The default value for HTTPError calls the custom error handler configured on the ServeMux via the
	// WithProtoErrorHandler serve option if that option was used, calling GlobalHTTPErrorHandler otherwise.
	//
	// To customize the error handling of a particular ServeMux instance, use the WithProtoErrorHandler
	// serve option.
	//
	// To customize the error format for all ServeMux instances not using the WithProtoErrorHandler serve
	// option, set GlobalHTTPErrorHandler to a custom function.
	//
	// Setting this variable directly to customize error format is deprecated.
	HTTPError = MuxOrGlobalHTTPError

	// GlobalHTTPErrorHandler is the HTTPError handler for all ServeMux instances not using the
	// WithProtoErrorHandler serve option.
	//
	// You can set a custom function to this variable to customize error format.
	GlobalHTTPErrorHandler = DefaultHTTPError

	// OtherErrorHandler handles gateway errors from parsing and routing client requests for all
	// ServeMux instances not using the WithProtoErrorHandler serve option.
	//
	// It returns the following error codes: StatusMethodNotAllowed StatusNotFound StatusBadRequest
	//
	// To customize parsing and routing error handling of a particular ServeMux instance, use the
	// WithProtoErrorHandler serve option.
	//
	// To customize parsing and routing error handling of all ServeMux instances not using the
	// WithProtoErrorHandler serve option, set a custom function to this variable.
	OtherErrorHandler = DefaultOtherErrorHandler
)
View Source
var (
	// ErrNotMatch indicates that the given HTTP request path does not match to the pattern.
	ErrNotMatch = errors.New("not match to the path pattern")
	// ErrInvalidPattern indicates that the given definition of Pattern is not valid.
	ErrInvalidPattern = errors.New("invalid pattern")
)
View Source
var (
	// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound
	// header isn't present. If the value is 0 the sent `context` will not have a timeout.
	DefaultContextTimeout = 0 * time.Second
)

ErrUnknownURI is the error supplied to a custom ProtoErrorHandlerFunc when a request is received with a URI path that does not match any registered service method.

Since gRPC servers return an "Unimplemented" code for requests with an unrecognized URI path, this error also has a gRPC "Unimplemented" code.

Functions

func AnnotateContext

func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error)

AnnotateContext adds context information such as metadata from the request.

At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For", except that the forwarded destination is not another HTTP service but rather a gRPC service.

func AnnotateIncomingContext added in v1.11.1

func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Request) (context.Context, error)

AnnotateIncomingContext adds context information such as metadata from the request. Attach metadata as incoming context.

func Bool

func Bool(val string) (bool, error)

Bool converts the given string representation of a boolean value into bool.

func BoolP

func BoolP(val string) (*bool, error)

BoolP parses the given string representation of a boolean value, and returns a pointer to a bool whose value is same as the parsed value.

func BoolSlice added in v1.5.0

func BoolSlice(val, sep string) ([]bool, error)

BoolSlice converts 'val' where individual booleans are separated by 'sep' into a bool slice.

func BoolValue added in v1.6.0

func BoolValue(val string) (*wrappers.BoolValue, error)

BoolValue well-known type support as wrapper around bool type

func Bytes added in v1.4.0

func Bytes(val string) ([]byte, error)

Bytes converts the given string representation of a byte sequence into a slice of bytes A bytes sequence is encoded in URL-safe base64 without padding

func BytesSlice added in v1.5.0

func BytesSlice(val, sep string) ([][]byte, error)

BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe base64 without padding, are separated by 'sep' into a slice of bytes slices slice.

func BytesValue added in v1.6.0

func BytesValue(val string) (*wrappers.BytesValue, error)

BytesValue well-known type support as wrapper around bytes[] type

func DefaultHTTPError

func DefaultHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error)

DefaultHTTPError is the default implementation of HTTPError. If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. If otherwise, it replies with http.StatusInternalServerError.

The response body returned by this function is a JSON object, which contains a member whose key is "error" and whose value is err.Error().

func DefaultHTTPProtoErrorHandler added in v1.3.0

func DefaultHTTPProtoErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, _ *http.Request, err error)

DefaultHTTPProtoErrorHandler is an implementation of HTTPError. If "err" is an error from gRPC system, the function replies with the status code mapped by HTTPStatusFromCode. If otherwise, it replies with http.StatusInternalServerError.

The response body returned by this function is a Status message marshaled by a Marshaler.

Do not set this function to HTTPError variable directly, use WithProtoErrorHandler option instead.

func DefaultHeaderMatcher added in v1.3.0

func DefaultHeaderMatcher(key string) (string, bool)

DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header keys (as specified by the IANA) to gRPC context with grpcgateway- prefix. HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing prefix 'Grpc-Metadata-'.

func DefaultOtherErrorHandler

func DefaultOtherErrorHandler(w http.ResponseWriter, _ *http.Request, msg string, code int)

DefaultOtherErrorHandler is the default implementation of OtherErrorHandler. It simply writes a string representation of the given error into "w".

func DisallowUnknownFields added in v1.9.3

func DisallowUnknownFields()

DisallowUnknownFields enables option in decoder (unmarshaller) to return an error when it finds an unknown field. This function must be called before using the JSON marshaller.

func DoubleValue added in v1.6.0

func DoubleValue(val string) (*wrappers.DoubleValue, error)

DoubleValue well-known type support as wrapper around float64 type

func Duration added in v1.3.1

func Duration(val string) (*duration.Duration, error)

Duration converts the given string into a timestamp.Duration.

func Enum added in v1.5.0

func Enum(val string, enumValMap map[string]int32) (int32, error)

Enum converts the given string into an int32 that should be type casted into the correct enum proto type.

func EnumSlice added in v1.5.0

func EnumSlice(val, sep string, enumValMap map[string]int32) ([]int32, error)

EnumSlice converts 'val' where individual enums are separated by 'sep' into a int32 slice. Each individual int32 should be type casted into the correct enum proto type.

func FieldMaskFromRequestBody added in v1.6.0

func FieldMaskFromRequestBody(r io.Reader, md *descriptor.DescriptorProto) (*field_mask.FieldMask, error)

FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body.

func Float32

func Float32(val string) (float32, error)

Float32 converts the given string representation of a floating point number into float32.

func Float32P

func Float32P(val string) (*float32, error)

Float32P parses the given string representation of a floating point number, and returns a pointer to a float32 whose value is same as the parsed number.

func Float32Slice added in v1.5.0

func Float32Slice(val, sep string) ([]float32, error)

Float32Slice converts 'val' where individual floating point numbers are separated by 'sep' into a float32 slice.

func Float64

func Float64(val string) (float64, error)

Float64 converts the given string representation into representation of a floating point number into float64.

func Float64P

func Float64P(val string) (*float64, error)

Float64P parses the given string representation of a floating point number, and returns a pointer to a float64 whose value is same as the parsed number.

func Float64Slice added in v1.5.0

func Float64Slice(val, sep string) ([]float64, error)

Float64Slice converts 'val' where individual floating point numbers are separated by 'sep' into a float64 slice.

func FloatValue added in v1.6.0

func FloatValue(val string) (*wrappers.FloatValue, error)

FloatValue well-known type support as wrapper around float32 type

func ForwardResponseMessage

func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error)

ForwardResponseMessage forwards the message "resp" from gRPC server to REST client.

func ForwardResponseStream

func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error)

ForwardResponseStream forwards the stream from gRPC server to REST client.

func HTTPStatusFromCode

func HTTPStatusFromCode(code codes.Code) int

HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto

func Int32

func Int32(val string) (int32, error)

Int32 converts the given string representation of an integer into int32.

func Int32P

func Int32P(val string) (*int32, error)

Int32P parses the given string representation of an integer and returns a pointer to a int32 whose value is same as the parsed integer.

func Int32Slice added in v1.5.0

func Int32Slice(val, sep string) ([]int32, error)

Int32Slice converts 'val' where individual integers are separated by 'sep' into a int32 slice.

func Int32Value added in v1.6.0

func Int32Value(val string) (*wrappers.Int32Value, error)

Int32Value well-known type support as wrapper around int32 type

func Int64

func Int64(val string) (int64, error)

Int64 converts the given string representation of an integer into int64.

func Int64P

func Int64P(val string) (*int64, error)

Int64P parses the given string representation of an integer and returns a pointer to a int64 whose value is same as the parsed integer.

func Int64Slice added in v1.5.0

func Int64Slice(val, sep string) ([]int64, error)

Int64Slice converts 'val' where individual integers are separated by 'sep' into a int64 slice.

func Int64Value added in v1.6.0

func Int64Value(val string) (*wrappers.Int64Value, error)

Int64Value well-known type support as wrapper around int64 type

func MarshalerForRequest

func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, outbound Marshaler)

MarshalerForRequest returns the inbound/outbound marshalers for this request. It checks the registry on the ServeMux for the MIME type set by the Content-Type header. If it isn't set (or the request Content-Type is empty), checks for "*". If there are multiple Content-Type headers set, choose the first one that it can exactly match in the registry. Otherwise, it follows the above logic for "*"/InboundMarshaler/OutboundMarshaler.

func MuxOrGlobalHTTPError added in v1.14.0

func MuxOrGlobalHTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error)

MuxOrGlobalHTTPError uses the mux-configured error handler, falling back to GlobalErrorHandler.

func NewServerMetadataContext

func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context

NewServerMetadataContext creates a new context with ServerMetadata

func PopulateFieldFromPath

func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error

PopulateFieldFromPath sets a value in a nested Protobuf structure. It instantiates missing protobuf fields as it goes.

func PopulateQueryParameters

func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error

PopulateQueryParameters parses query parameters into "msg" using current query parser

func SetHTTPBodyMarshaler added in v1.8.4

func SetHTTPBodyMarshaler(serveMux *ServeMux)

SetHTTPBodyMarshaler overwrite the default marshaler with the HTTPBodyMarshaler

func String

func String(val string) (string, error)

String just returns the given string. It is just for compatibility to other types.

func StringP

func StringP(val string) (*string, error)

StringP returns a pointer to a string whose pointee is same as the given string value.

func StringSlice added in v1.5.0

func StringSlice(val, sep string) ([]string, error)

StringSlice converts 'val' where individual strings are separated by 'sep' into a string slice.

func StringValue added in v1.6.0

func StringValue(val string) (*wrappers.StringValue, error)

StringValue well-known type support as wrapper around string type

func Timestamp added in v1.3.1

func Timestamp(val string) (*timestamp.Timestamp, error)

Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp.

func UInt32Value added in v1.6.0

func UInt32Value(val string) (*wrappers.UInt32Value, error)

UInt32Value well-known type support as wrapper around uint32 type

func UInt64Value added in v1.6.0

func UInt64Value(val string) (*wrappers.UInt64Value, error)

UInt64Value well-known type support as wrapper around uint64 type

func Uint32

func Uint32(val string) (uint32, error)

Uint32 converts the given string representation of an integer into uint32.

func Uint32P

func Uint32P(val string) (*uint32, error)

Uint32P parses the given string representation of an integer and returns a pointer to a uint32 whose value is same as the parsed integer.

func Uint32Slice added in v1.5.0

func Uint32Slice(val, sep string) ([]uint32, error)

Uint32Slice converts 'val' where individual integers are separated by 'sep' into a uint32 slice.

func Uint64

func Uint64(val string) (uint64, error)

Uint64 converts the given string representation of an integer into uint64.

func Uint64P

func Uint64P(val string) (*uint64, error)

Uint64P parses the given string representation of an integer and returns a pointer to a uint64 whose value is same as the parsed integer.

func Uint64Slice added in v1.5.0

func Uint64Slice(val, sep string) ([]uint64, error)

Uint64Slice converts 'val' where individual integers are separated by 'sep' into a uint64 slice.

Types

type Decoder

type Decoder interface {
	Decode(v interface{}) error
}

Decoder decodes a byte sequence

type DecoderFunc

type DecoderFunc func(v interface{}) error

DecoderFunc adapts an decoder function into Decoder.

func (DecoderFunc) Decode

func (f DecoderFunc) Decode(v interface{}) error

Decode delegates invocations to the underlying function itself.

type DecoderWrapper added in v1.4.0

type DecoderWrapper struct {
	*json.Decoder
}

DecoderWrapper is a wrapper around a *json.Decoder that adds support for protos to the Decode method.

func (DecoderWrapper) Decode added in v1.4.0

func (d DecoderWrapper) Decode(v interface{}) error

Decode wraps the embedded decoder's Decode method to support protos using a jsonpb.Unmarshaler.

type Delimited added in v1.3.1

type Delimited interface {
	// Delimiter returns the record separator for the stream.
	Delimiter() []byte
}

Delimited defines the streaming delimiter.

type Encoder

type Encoder interface {
	Encode(v interface{}) error
}

Encoder encodes gRPC payloads / fields into byte sequence.

type EncoderFunc

type EncoderFunc func(v interface{}) error

EncoderFunc adapts an encoder function into Encoder

func (EncoderFunc) Encode

func (f EncoderFunc) Encode(v interface{}) error

Encode delegates invocations to the underlying function itself.

type HTTPBodyMarshaler added in v1.8.4

type HTTPBodyMarshaler struct {
	Marshaler
}

HTTPBodyMarshaler is a Marshaler which supports marshaling of a google.api.HttpBody message as the full response body if it is the actual message used as the response. If not, then this will simply fallback to the Marshaler specified as its default Marshaler.

func (*HTTPBodyMarshaler) ContentType added in v1.8.4

func (h *HTTPBodyMarshaler) ContentType() string

ContentType implementation to keep backwards compatibility with marshal interface

func (*HTTPBodyMarshaler) ContentTypeFromMessage added in v1.8.4

func (h *HTTPBodyMarshaler) ContentTypeFromMessage(v interface{}) string

ContentTypeFromMessage in case v is a google.api.HttpBody message it returns its specified content type otherwise fall back to the default Marshaler.

func (*HTTPBodyMarshaler) Marshal added in v1.8.4

func (h *HTTPBodyMarshaler) Marshal(v interface{}) ([]byte, error)

Marshal marshals "v" by returning the body bytes if v is a google.api.HttpBody message, otherwise it falls back to the default Marshaler.

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string)

A HandlerFunc handles a specific pair of path pattern and HTTP method.

type HeaderMatcherFunc added in v1.3.0

type HeaderMatcherFunc func(string) (string, bool)

HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context.

type JSONBuiltin

type JSONBuiltin struct{}

JSONBuiltin is a Marshaler which marshals/unmarshals into/from JSON with the standard "encoding/json" package of Golang. Although it is generally faster for simple proto messages than JSONPb, it does not support advanced features of protobuf, e.g. map, oneof, ....

The NewEncoder and NewDecoder types return *json.Encoder and *json.Decoder respectively.

func (*JSONBuiltin) ContentType

func (*JSONBuiltin) ContentType() string

ContentType always Returns "application/json".

func (*JSONBuiltin) Delimiter added in v1.3.1

func (j *JSONBuiltin) Delimiter() []byte

Delimiter for newline encoded JSON streams.

func (*JSONBuiltin) Marshal

func (j *JSONBuiltin) Marshal(v interface{}) ([]byte, error)

Marshal marshals "v" into JSON

func (*JSONBuiltin) NewDecoder

func (j *JSONBuiltin) NewDecoder(r io.Reader) Decoder

NewDecoder returns a Decoder which reads JSON stream from "r".

func (*JSONBuiltin) NewEncoder

func (j *JSONBuiltin) NewEncoder(w io.Writer) Encoder

NewEncoder returns an Encoder which writes JSON stream into "w".

func (*JSONBuiltin) Unmarshal

func (j *JSONBuiltin) Unmarshal(data []byte, v interface{}) error

Unmarshal unmarshals JSON data into "v".

type JSONPb

type JSONPb jsonpb.Marshaler

JSONPb is a Marshaler which marshals/unmarshals into/from JSON with the "github.com/golang/protobuf/jsonpb". It supports fully functionality of protobuf unlike JSONBuiltin.

The NewDecoder method returns a DecoderWrapper, so the underlying *json.Decoder methods can be used.

func (*JSONPb) ContentType

func (*JSONPb) ContentType() string

ContentType always returns "application/json".

func (*JSONPb) Delimiter added in v1.3.1

func (j *JSONPb) Delimiter() []byte

Delimiter for newline encoded JSON streams.

func (*JSONPb) Marshal

func (j *JSONPb) Marshal(v interface{}) ([]byte, error)

Marshal marshals "v" into JSON.

func (*JSONPb) NewDecoder

func (j *JSONPb) NewDecoder(r io.Reader) Decoder

NewDecoder returns a Decoder which reads JSON stream from "r".

func (*JSONPb) NewEncoder

func (j *JSONPb) NewEncoder(w io.Writer) Encoder

NewEncoder returns an Encoder which writes JSON stream into "w".

func (*JSONPb) Unmarshal

func (j *JSONPb) Unmarshal(data []byte, v interface{}) error

Unmarshal unmarshals JSON "data" into "v"

type Marshaler

type Marshaler interface {
	// Marshal marshals "v" into byte sequence.
	Marshal(v interface{}) ([]byte, error)
	// Unmarshal unmarshals "data" into "v".
	// "v" must be a pointer value.
	Unmarshal(data []byte, v interface{}) error
	// NewDecoder returns a Decoder which reads byte sequence from "r".
	NewDecoder(r io.Reader) Decoder
	// NewEncoder returns an Encoder which writes bytes sequence into "w".
	NewEncoder(w io.Writer) Encoder
	// ContentType returns the Content-Type which this marshaler is responsible for.
	ContentType() string
}

Marshaler defines a conversion between byte sequence and gRPC payloads / fields.

type Pattern

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

Pattern is a template pattern of http request paths defined in github.com/googleapis/googleapis/google/api/http.proto.

func MustPattern

func MustPattern(p Pattern, err error) Pattern

MustPattern is a helper function which makes it easier to call NewPattern in variable initialization.

func NewPattern

func NewPattern(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error)

NewPattern returns a new Pattern from the given definition values. "ops" is a sequence of op codes. "pool" is a constant pool. "verb" is the verb part of the pattern. It is empty if the pattern does not have the part. "version" must be 1 for now. It returns an error if the given definition is invalid.

func (Pattern) Match

func (p Pattern) Match(components []string, verb string) (map[string]string, error)

Match examines components if it matches to the Pattern. If it matches, the function returns a mapping from field paths to their captured values. If otherwise, the function returns an error.

func (Pattern) String

func (p Pattern) String() string

func (Pattern) Verb

func (p Pattern) Verb() string

Verb returns the verb part of the Pattern.

type PatternOpt added in v1.9.2

type PatternOpt func(*patternOptions)

PatternOpt is an option for creating Patterns.

func AssumeColonVerbOpt added in v1.9.2

func AssumeColonVerbOpt(val bool) PatternOpt

AssumeColonVerbOpt indicates whether a path suffix after a final colon may only be interpreted as a verb.

type ProtoErrorHandlerFunc added in v1.3.0

type ProtoErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error)

ProtoErrorHandlerFunc handles the error as a gRPC error generated via status package and replies to the request.

type ProtoMarshaller added in v1.3.1

type ProtoMarshaller struct{}

ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes

func (*ProtoMarshaller) ContentType added in v1.3.1

func (*ProtoMarshaller) ContentType() string

ContentType always returns "application/octet-stream".

func (*ProtoMarshaller) Marshal added in v1.3.1

func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error)

Marshal marshals "value" into Proto

func (*ProtoMarshaller) NewDecoder added in v1.3.1

func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder

NewDecoder returns a Decoder which reads proto stream from "reader".

func (*ProtoMarshaller) NewEncoder added in v1.3.1

func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder

NewEncoder returns an Encoder which writes proto stream into "writer".

func (*ProtoMarshaller) Unmarshal added in v1.3.1

func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error

Unmarshal unmarshals proto "data" into "value"

type QueryParameterParser added in v1.14.0

type QueryParameterParser interface {
	Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error
}

QueryParameterParser defines interface for all query parameter parsers

type ServeMux

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

ServeMux is a request multiplexer for grpc-gateway. It matches http requests to patterns and invokes the corresponding handler.

func NewServeMux

func NewServeMux(opts ...ServeMuxOption) *ServeMux

NewServeMux returns a new ServeMux whose internal mapping is empty.

func (*ServeMux) GetForwardResponseOptions

func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.ResponseWriter, proto.Message) error

GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux.

func (*ServeMux) Handle

func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc)

Handle associates "h" to the pair of HTTP method and path pattern.

func (*ServeMux) ServeHTTP

func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path.

type ServeMuxOption

type ServeMuxOption func(*ServeMux)

ServeMuxOption is an option that can be given to a ServeMux on construction.

func SetQueryParameterParser added in v1.14.0

func SetQueryParameterParser(queryParameterParser QueryParameterParser) ServeMuxOption

SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. Configuring this will mean the generated swagger output is no longer correct, and it should be done with careful consideration.

func WithDisablePathLengthFallback added in v1.7.0

func WithDisablePathLengthFallback() ServeMuxOption

WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback.

func WithForwardResponseOption

func WithForwardResponseOption(forwardResponseOption func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption

WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption.

forwardResponseOption is an option that will be called on the relevant context.Context, http.ResponseWriter, and proto.Message before every forwarded response.

The message may be nil in the case where just a header is being sent.

func WithIncomingHeaderMatcher added in v1.3.0

func WithIncomingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption

WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.

This matcher will be called with each header in http.Request. If matcher returns true, that header will be passed to gRPC context. To transform the header before passing to gRPC context, matcher should return modified header.

func WithLastMatchWins added in v1.9.2

func WithLastMatchWins() ServeMuxOption

WithLastMatchWins returns a ServeMuxOption that will enable "last match wins" behavior, where if multiple path patterns match a request path, the last one defined in the .proto file will be used.

func WithMarshalerOption

func WithMarshalerOption(mime string, marshaler Marshaler) ServeMuxOption

WithMarshalerOption returns a ServeMuxOption which associates inbound and outbound Marshalers to a MIME type in mux.

func WithMetadata added in v1.3.0

func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) ServeMuxOption

WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context.

This can be used by services that need to read from http.Request and modify gRPC context. A common use case is reading token from cookie and adding it in gRPC context.

func WithOutgoingHeaderMatcher added in v1.3.0

func WithOutgoingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption

WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway.

This matcher will be called with each header in response header metadata. If matcher returns true, that header will be passed to http response returned from gateway. To transform the header before passing to response, matcher should return modified header.

func WithProtoErrorHandler added in v1.3.0

func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption

WithProtoErrorHandler returns a ServeMuxOption for configuring a custom error handler.

This can be used to handle an error as general proto message defined by gRPC. When this option is used, the mux uses the configured error handler instead of HTTPError and OtherErrorHandler.

func WithStreamErrorHandler added in v1.9.0

func WithStreamErrorHandler(fn StreamErrorHandlerFunc) ServeMuxOption

WithStreamErrorHandler returns a ServeMuxOption that will use the given custom stream error handler, which allows for customizing the error trailer for server-streaming calls.

For stream errors that occur before any response has been written, the mux's ProtoErrorHandler will be invoked. However, once data has been written, the errors must be handled differently: they must be included in the response body. The response body's final message will include the error details returned by the stream error handler.

type ServerMetadata

type ServerMetadata struct {
	HeaderMD  metadata.MD
	TrailerMD metadata.MD
}

ServerMetadata consists of metadata sent from gRPC server.

func ServerMetadataFromContext

func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool)

ServerMetadataFromContext returns the ServerMetadata in ctx

type ServerTransportStream added in v1.14.8

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

ServerTransportStream implements grpc.ServerTransportStream. It should only be used by the generated files to support grpc.SendHeader outside of gRPC server use.

func (*ServerTransportStream) Header added in v1.14.8

func (s *ServerTransportStream) Header() metadata.MD

Header returns the header metadata of the stream.

func (*ServerTransportStream) Method added in v1.14.8

func (s *ServerTransportStream) Method() string

Method returns the method for the stream.

func (*ServerTransportStream) SendHeader added in v1.14.8

func (s *ServerTransportStream) SendHeader(md metadata.MD) error

SendHeader sets the header metadata.

func (*ServerTransportStream) SetHeader added in v1.14.8

func (s *ServerTransportStream) SetHeader(md metadata.MD) error

SetHeader sets the header metadata.

func (*ServerTransportStream) SetTrailer added in v1.14.8

func (s *ServerTransportStream) SetTrailer(md metadata.MD) error

SetTrailer sets the trailer metadata.

func (*ServerTransportStream) Trailer added in v1.14.8

func (s *ServerTransportStream) Trailer() metadata.MD

Trailer returns the cached trailer metadata.

type StreamError added in v1.9.0

type StreamError internal.StreamError

StreamError is the payload for the final message in a server stream in the event that the server returns an error after a response message has already been sent.

func DefaultHTTPStreamErrorHandler added in v1.9.0

func DefaultHTTPStreamErrorHandler(_ context.Context, err error) *StreamError

DefaultHTTPStreamErrorHandler converts the given err into a *StreamError via default logic.

It extracts the gRPC status from err if possible. The fields of the status are used to populate the returned StreamError, and the HTTP status code is derived from the gRPC code via HTTPStatusFromCode. If the given err does not contain a gRPC status, an "Unknown" gRPC code is used and "Internal Server Error" HTTP code.

type StreamErrorHandlerFunc added in v1.9.0

type StreamErrorHandlerFunc func(context.Context, error) *StreamError

StreamErrorHandlerFunc accepts an error as a gRPC error generated via status package and translates it into a a proto struct used to represent error at the end of a stream.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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