Documentation
¶
Overview ¶
Package vanguard provides REST support for services built on connectrpc.com/connect/v2.
When a Protobuf method is annotated with a google.api.http rule, it declares the HTTP method, URL path, and body mapping for that RPC. Vanguard implements these rules in both directions:
- Mount exposes a connect.Server over REST, allowing standard HTTP clients to reach handlers written against generated RPC interfaces.
- NewTransport returns a connect.Transport that speaks REST, allowing generated RPC clients to call a REST server that knows nothing about Connect.
Vanguard acts as a peer to connect-go's connecthttp package. While connecthttp serves the Connect, gRPC, and gRPC-Web protocols, Vanguard handles REST. Because Mount takes the same multiplexer interface as connecthttp.Mount, and NewTransport takes the same HTTP client, REST can be seamlessly added without disturbing existing protocols.
Request and response bodies may be compressed, negotiated through the standard Content-Encoding and Accept-Encoding headers. gzip is supported by default. See WithCompressors.
Streaming RPCs are carried over REST when the streamed side is a google.api.HttpBody: a client stream's request body is the whole HTTP request body, and a server stream writes one chunk per message to the HTTP response body. Bidirectional streams have no REST mapping.
Server side:
server := connect.NewServer()
pingv1connect.RegisterPingServiceHandler(server, &pingServer{})
mux := http.NewServeMux()
connecthttp.Mount(mux, server) // Connect, gRPC, gRPC-Web
vanguard.Mount(mux, server) // google.api.http (REST)
Client side:
transport, _ := vanguard.NewTransport(http.DefaultClient, "https://api.example.com")
client := pingv1connect.NewPingServiceClient(connect.NewClient(transport))
resp, err := client.Ping(ctx, &pingv1.PingRequest{Number: 42})
Proxy, with no generated code for the service:
upstream := connect.NewClient(connecthttp.NewTransport(http.DefaultClient, backendURL)) server.Register(vanguard.ForwardService(upstream, serviceDescriptor)...) vanguard.Mount(mux, server)
Index ¶
- func Forward(client *connect.Client, desc protoreflect.MethodDescriptor) connect.Method
- func ForwardService(client *connect.Client, service protoreflect.ServiceDescriptor) []connect.Method
- func Mount(mux connecthttp.ServeMux, server *connect.Server, opts ...Option) error
- func NewTransport(httpClient connecthttp.HTTPClient, baseURL string, opts ...Option) (connect.Transport, error)
- type JSONCodec
- type Option
- func WithCodec(newCodec func(connectproto.TypeResolver) RESTCodec) Option
- func WithCompressors(compressors ...connect.Compressor) Option
- func WithDiscardUnknownQueryParams(discard bool) Option
- func WithMaxReadBytes(n int64) Option
- func WithRules(rules ...*annotations.HttpRule) Option
- func WithSendCompression(name string) Option
- func WithTypeResolver(resolver connectproto.TypeResolver) Option
- type RESTCodec
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Forward ¶ added in v0.5.0
func Forward(client *connect.Client, desc protoreflect.MethodDescriptor) connect.Method
Forward returns a connect.Method that relays calls for desc to client. Metadata and errors pass through in both directions. Messages are instantiated from desc, so a proxy needs no generated code.
func ForwardService ¶ added in v0.5.0
func ForwardService(client *connect.Client, service protoreflect.ServiceDescriptor) []connect.Method
ForwardService returns a Forward method for every RPC of service.
func Mount ¶ added in v0.5.0
Mount installs Vanguard's REST router onto mux. Methods registered on the server that carry a google.api.http annotation (or one supplied via WithRules) become REST endpoints. Methods without a rule are silently skipped. A rule on a streaming method whose streamed side is not a google.api.HttpBody is an error.
The mux interface is the same connecthttp.ServeMux used by connecthttp.Mount. This allows a single *http.ServeMux to host Connect, gRPC, and REST routes simultaneously.
Vanguard installs a single catch-all "/" handler rather than per-pattern routes, because google.api.http templates support syntax (like `**`, single-segment `*`, and `:verb` suffixes) that net/http's pattern matcher does not. To scope this catch-all, mount Vanguard on a sub-mux (e.g., `mux.Handle("/api/", subMux)`).
Dispatch flows through connect.Server.Call, ensuring any interceptors registered on the server fire as expected. HTTP has no trailers in this binding, so metadata set on the CallInfo's ResponseTrailer is discarded.
func NewTransport ¶ added in v0.5.0
func NewTransport(httpClient connecthttp.HTTPClient, baseURL string, opts ...Option) (connect.Transport, error)
NewTransport returns a connect.Transport that issues REST requests for procedures with a google.api.http annotation (or one supplied via WithRules).
The httpClient takes the same interface as connecthttp.NewTransport (typically an *http.Client). If nil, http.DefaultClient is used.
Each call to NewClientStream resolves the procedure's HTTP rule from the provided Spec. Calling an unknown procedure, or one without an HTTP rule, returns connect.CodeUnimplemented.
Types ¶
type JSONCodec ¶
type JSONCodec struct {
connectproto.JSONCodec
}
JSONCodec implements connect.Codec, connect.StableCodec, and RESTCodec for the JSON format. It embeds connectproto.JSONCodec for its implementation.
func NewJSONCodec ¶
func NewJSONCodec(res connectproto.TypeResolver) *JSONCodec
NewJSONCodec is the default codec factory for the "json" codec. The provided resolver is used to unmarshal extensions and to marshal/unmarshal instances of google.protobuf.Any.
By default, the returned codec emits unpopulated fields when marshaling and discards unknown fields when unmarshaling.
func (*JSONCodec) MarshalAppendField ¶
func (j *JSONCodec) MarshalAppendField(_ context.Context, base []byte, msg proto.Message, field protoreflect.FieldDescriptor) ([]byte, error)
MarshalAppendField implements RESTCodec.
func (*JSONCodec) UnmarshalField ¶
func (j *JSONCodec) UnmarshalField(_ context.Context, data []byte, msg proto.Message, field protoreflect.FieldDescriptor) error
UnmarshalField implements RESTCodec.
type Option ¶ added in v0.5.0
type Option interface {
// contains filtered or unexported methods
}
Option configures the REST handler installed by Mount or NewTransport.
func WithCodec ¶
func WithCodec(newCodec func(connectproto.TypeResolver) RESTCodec) Option
WithCodec overrides the RESTCodec factory used to encode and decode bodies. The factory is invoked once per Mount or NewTransport call, after option processing, with the resolver chosen by WithTypeResolver (or protoregistry.GlobalTypes if none).
// Use the default JSON codec but configure it.
vanguard.Mount(mux, server,
vanguard.WithCodec(func(r connectproto.TypeResolver) vanguard.RESTCodec {
c := vanguard.NewJSONCodec(r)
c.MarshalOptions.UseProtoNames = true
return c
}),
)
func WithCompressors ¶ added in v0.5.0
func WithCompressors(compressors ...connect.Compressor) Option
WithCompressors configures the compression algorithms available for request and response bodies, keyed by their Content-Encoding token. A handler decompresses requests sent with a known encoding and compresses responses using the request's encoding, or else the first Accept-Encoding token it supports. A transport advertises the names in Accept-Encoding and decompresses responses.
Calling WithCompressors with no arguments disables compression entirely. If multiple compressors share the same name, only the first is kept.
The default is gzip.
func WithDiscardUnknownQueryParams ¶ added in v0.5.0
WithDiscardUnknownQueryParams controls whether unknown query parameters are ignored when decoding a REST request. By default (false), unknown parameters return an error.
func WithMaxReadBytes ¶ added in v0.5.0
WithMaxReadBytes caps the size of a body read off the wire: the request body for Mount, the response body for NewTransport, measured after any decompression. Bodies exceeding this limit fail with CodeResourceExhausted. The default is 4 MiB. Zero allows any size.
func WithRules ¶
func WithRules(rules ...*annotations.HttpRule) Option
WithRules attaches HTTP rules that are not embedded directly as google.api.http annotations on the method descriptors. Each rule's selector must match a registered procedure (the fully-qualified method name).
func WithSendCompression ¶ added in v0.5.0
WithSendCompression configures a transport to compress request bodies using the named algorithm, which must be registered via WithCompressors (or be the default gzip compressor).
By default, transports send uncompressed requests. Mount ignores this option.
func WithTypeResolver ¶
func WithTypeResolver(resolver connectproto.TypeResolver) Option
WithTypeResolver overrides the proto type resolver used when instantiating request and response messages. Defaults to protoregistry.GlobalTypes.
type RESTCodec ¶
type RESTCodec interface {
connect.Codec
// MarshalAppendField marshals just the given field of the given message to
// bytes, and appends it to the given base byte slice.
MarshalAppendField(ctx context.Context, base []byte, msg proto.Message, field protoreflect.FieldDescriptor) ([]byte, error)
// UnmarshalField unmarshals the given data into the given field of the given
// message.
UnmarshalField(ctx context.Context, data []byte, msg proto.Message, field protoreflect.FieldDescriptor) error
}
RESTCodec extends connect.Codec with methods for marshaling and unmarshaling individual message fields. This supports query string variables and body mappings that target specific fields rather than the entire message. These extra methods are only used by the REST protocol.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
examples/fileserver
command
This program serves a directory of files via a Connect-shaped ContentService and exposes that service over REST using vanguard.
|
This program serves a directory of files via a Connect-shaped ContentService and exposes that service over REST using vanguard. |
|
examples/petstore
command
This program calls the live Swagger Petstore service at https://petstore.swagger.io/v2/ using a Connect-shaped RPC client.
|
This program calls the live Swagger Petstore service at https://petstore.swagger.io/v2/ using a Connect-shaped RPC client. |
|
examples/proxy
command
This program puts a REST front end on an RPC backend it has no Go types for.
|
This program puts a REST front end on an RPC backend it has no Go types for. |
|
gen/io/swagger/petstore/v2/petstorev2connect
The service defined herein comes from v2 of the Petstore service, which is used as an example for Swagger/OpenAPI.
|
The service defined herein comes from v2 of the Petstore service, which is used as an example for Swagger/OpenAPI. |
|
Package vanguardgrpc bridges google.golang.org/grpc generated stubs into a connectrpc.com/connect/v2 Server.
|
Package vanguardgrpc bridges google.golang.org/grpc generated stubs into a connectrpc.com/connect/v2 Server. |