resttools

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// CharsField contains the characters allowed in a field name (URL path or body)
	CharsField = `-_.0-9a-zA-Z`

	// CharsLiteral contains the the characters allowed in a URL path literal segment.
	CharsLiteral = `-_.~0-9a-zA-Z%`

	// RegexURLPathSingleSegmentValue contains the regex expression for matching a single URL
	// path segment (i.e. `/` is not allowed). Since gorilla/mux hands uses the decoded paths to
	// match, we can just accept any characters.
	RegexURLPathSingleSegmentValue = "[^:]+"

	// RegexURLPathSingleSegmentValue contains the regex expression for matching multiple URL
	// path segments (i.e. `/` is allowed). Since gorilla/mux hands uses the decoded paths to
	// match, we can just accept any characters.
	RegexURLPathMultipleSegmentValue = "[^:]+"
)
View Source
const ServerStreamingChunkSize = 30

Variables

View Source
var (
	// CharsFieldPath contains the characters allowed in a dotted field path.
	CharsFieldPath string

	// RegexField contains the regex expression for matching a single (not nested) field name.
	RegexField string

	// RegexField contains the regex expression for matching a dotted field path.
	RegexFieldPath string

	// RegexLiteral contains the regex expression for matching a URL path literal segment.
	RegexLiteral string
)

Functions

func CheckAPIClientHeader added in v0.16.0

func CheckAPIClientHeader(header http.Header) error

CheckAPIClientHeader verifies that the "x-goog-api-client" header contains the expected tokens ("rest/..." and "gapic/...").

func CheckContentType added in v0.15.0

func CheckContentType(header http.Header) error

CheckContentType checks header to ensure the expected JSON content type is specified.

func CheckEnum added in v0.14.0

func CheckEnum(payload jsonPayload, fieldPath []protoreflect.Name) (fieldName string, ok bool)

CheckEnum verifies whether the field whose qualified name is captured in the elements of fieldPath has a string value, if it exists, in the JSON representation captured by payload. This returns the qualified field name (as present as it is in payload) as a single string, and a boolean that is true only if either fieldPath is not present or if its value is a string. This means that if fieldPath is a path to an enum field, the boolean will be false if the enum is encoded in the payload using a non-string representation.

func CheckFieldNames added in v0.14.0

func CheckFieldNames(payload jsonPayload) error

CheckFieldNames checks that the field names in the JSON request body are properly formatted (lower-camel-cased).

func CheckJSONEnumFields added in v0.14.0

func CheckJSONEnumFields(payload jsonPayload, fieldsToCheck [][]protoreflect.Name) error

CheckJSONEnumFields verifies that each of the fields listed in fieldsToCheck, presumably all referring to enum fields, are encoded correctly in the parsed JSON payload, meaning that the field is absent or its value is a string. Each element of fieldsToCheck is a qualified proto field name represented as a sequence of simple protoreflect.Name.

func CheckRequestFormat added in v0.15.0

func CheckRequestFormat(jsonReader io.Reader, request *http.Request, message protoreflect.Message) error

CheckRequestFormat verifies that the incoming request has the correct format in its body (via jsonReader) and in its HTTP headers.

func ComputeEnumFields added in v0.14.0

func ComputeEnumFields(message protoreflect.Message) [][]protoreflect.Name

ComputeEnumFields determines which fields in message or its submessages are enums, and returns a list of those qualified field names (each one of those being a list of simple protoreflect.Name).

func ErrorResponse added in v0.20.0

func ErrorResponse(w http.ResponseWriter, status int, message string, details ...interface{})

ErrorResponse is a helper that formats the given response information, including the HTTP Status code, a message, and any error detail types, into a googleAPIError and writes the response as JSON.

func FromJSON added in v0.14.0

func FromJSON() *protojson.UnmarshalOptions

FromJSON returns a copy of the current global JSON unmarshaling options. Modifications to this copy do not change the values of these options returned in subsequent calls to this function. This is the function Showcase REST endpoints should use to handle JSON unmarshaling.

func GRPCToHTTP added in v0.20.0

func GRPCToHTTP(c codes.Code) int

GRPCToHTTP maps the given gRPC Code to the canonical HTTP Status code as defined by the internal source go/http-canonical-mapping.

func GetEnumFields added in v0.14.0

func GetEnumFields(message protoreflect.Message) [][]protoreflect.Name

GetEnumFields returns a list of any arbitrarily nested fields in message that are enums. Each member of the returned list is a qualified field name, itself represented as a list of simple protoreflect.Name.

func IncludeRequestHeadersInResponse added in v0.35.0

func IncludeRequestHeadersInResponse(w http.ResponseWriter, r *http.Request)

IncludeRequestHeadersInResponse includes all headers in the request `r` and includes them in the response `w`, prefixing each of these header keys with a constant to reflect they came from the request.

func KeysMatchPath

func KeysMatchPath(examine map[string][]string, lookFor []string) []string

KeysMatchPath returns the keys in `examine` that match any of the elements in `lookFor`, interpreting the latter as dotted-field paths. This means a match occurs when (a) the two are identical, or (b) when any element of `lookFor` is a prefix of the `examine` key and is followed by a period. For example: KeysMatchPath(map[string][]string{"loc": nil, "loc.lat": nil, "location":nil},

         []string{"loc"})
== []string{"loc","loc.lat"}

func PopulateFields

func PopulateFields(protoMessage proto.Message, fieldValues map[string][]string) error

PopulateFields sets the fields within protoMessage to the values provided in fieldValues. The fields and values are provided as a map of field paths to lists of string representations of their values. The field paths can refer to fields nested arbitrarily deep within protoMessage; each path element must be lower-camel-cased. `fieldValues` contains the list of values applicable to the field: a single value of singular fields, or ordered values for a repeated field. This returns an error if any field path is not valid or if any value can't be parsed into the correct data type for the field.

func PopulateOneField

func PopulateOneField(protoMessage proto.Message, fieldPath string, fieldValues []string) error

PopulateOneField finds in protoMessage the field identified by fieldPath (which could refer to an arbitrarily nested field using dotted notation; each path element must be lower-camel-cased) and sets it to `value`. It returns an error if the fieldPath does not properly reference a field, or if `fieldValues` could not be parsed into a list of the data type expected for the field. `fieldValues` is a slice to allow passing a series of repeated field entries.

func PopulateRequestHeaders added in v0.15.0

func PopulateRequestHeaders(request *http.Request)

PopulateRequestHeaders inspects request and adds the correct headers. This is useful for tests where we're not trying to send incorrect headers.

func PopulateSingularFields

func PopulateSingularFields(protoMessage proto.Message, fieldValues map[string]string) error

PopulateSingularFields sets the fields within protoMessage to the values provided in fieldValues. The fields and values are provided as a map of field paths to the string representation of their values. The field paths can refer to fields nested arbitrarily deep within protoMessage; each path element must be lower-camel-cased. This returns an error if any field path is not valid or if any value can't be parsed into the correct data type for the field.

func PrettyPrintHeaders added in v0.33.0

func PrettyPrintHeaders(request *http.Request, indentation string) string

PrettyPrintHeaders prints all the HTTP headers in `request` in lines preceded by `indentation`. Each line has one header key and a quoted list of all values for that key.

func ToDottedLowerCamel added in v0.14.0

func ToDottedLowerCamel(fieldPath string) string

ToDottedLowerCamel converts each segment of a dot-delimited fieldPath to be individually lower-camel-cased; the dots are preserved.

func ToJSON added in v0.14.0

func ToJSON() *protojson.MarshalOptions

ToJSON returns a copy of the current global JSON marshaling options in JSONMarshaler. Modifications to this copy do not change the values of these options returned in subsequent calls to this function. This is the function Showcase REST endpoints should use to handle JSON marshaling.

Types

type BindingURIKeyType added in v0.23.0

type BindingURIKeyType string

A key-type for storing binding URI value in the Context

const BindingURIKey BindingURIKeyType = BindingURIKeyType("BindingURIKey")

type JSONMarshalOptions added in v0.14.0

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

JSONMarshalOptions contains the current JSON marshaling options used by REST endpoints, and allows for temporarily replacing these global options and then restoring them. This functionality is useful for some tests.

var JSONMarshaler JSONMarshalOptions

JSONMarshaler captures the JSON marshaling options. It is intended only for tests of Showcase functionality (not for normal Showcase use or tests of generators against Showcase).

func (*JSONMarshalOptions) Replace added in v0.14.0

func (jm *JSONMarshalOptions) Replace(opt *protojson.MarshalOptions)

Replace replaces the current JSON marshaling options with those provided by opt. Call Restore() to restore the production options. Only one replacement can be active at a time; subsequent calls hang waiting for the first call's mutex to be released.

As a special case, if opt==nil, the replacement is with the production options themselves; this is useful for tests that need to lock the production options to protect from other tests which may need to change them.

func (*JSONMarshalOptions) Restore added in v0.14.0

func (jm *JSONMarshalOptions) Restore()

Restore restores the production JSON marshaling options. There must be an active Replace() called previously.

type ServerStreamer added in v0.17.0

type ServerStreamer struct {
	grpc.ServerStream
	// contains filtered or unexported fields
}

ServerStreamer implements REST server streaming functionality that can be called by streaming RPCs to stream their responses over HTTP/JSON. The messages are encoded such that once the stream is finished, the total payload represents a properly formed JSON array of objects. In order to ensure this, users must call the End() method to terminate the stream properly, typically by using `defer`.

func NewServerStreamer added in v0.17.0

func NewServerStreamer(responseWriter io.Writer, chunkSize int) (*ServerStreamer, error)

NewServerStreamer returns a ServerStreamer instance initialized to write to responseWriter. Users must call the End() method to terminate the stream properly, typically by using `defer`. Note that responseWriter must also be an http.Flusher. If chunkSize is positive, messages written to this ServerStreamer are chunked-encoded into chunks of size chunkSize (except for the final chunk, which could be smaller). If chunkSize is zero, each message is written into a single chunk.

func (*ServerStreamer) Context added in v0.17.0

func (streamer *ServerStreamer) Context() context.Context

Context is needed to satisfy grpc.ServerStream.

func (*ServerStreamer) End added in v0.17.0

func (streamer *ServerStreamer) End() error

End terminates the REST stream by sending the trailing bytes (the closing bracket for the array).

func (*ServerStreamer) Send added in v0.17.0

func (streamer *ServerStreamer) Send(message proto.Message) error

Send sends a `message` over the REST stream using chunked-encoding according to the constructor chunkSize parameter.

type SystemParameters added in v0.21.0

type SystemParameters struct {
	EnumEncodingAsInt bool
}

SystemParameters encapsulates the system parameters recognized by Showcase. These are a subset of Google's accepted system parameters described in https://cloud.google.com/apis/docs/system-parameters.

func GetSystemParameters added in v0.21.0

func GetSystemParameters(request *http.Request) (systemParams *SystemParameters, queryParams map[string][]string, err error)

GetSystemParameters returns the SystemParameters encoded in request, and the query parameters in the request's query string that are not themselves system parameters.

Jump to

Keyboard shortcuts

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