vanguard

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 32 Imported by: 50 modules, 27 packages
Image

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Image README

⚔️ Vanguard

Build GoDoc Slack

Vanguard adds REST to connect-go services. Using Google's HTTP transcoding options, it maps each RPC to an HTTP method, URL path, and JSON body from its strongly typed Protobuf definition. connect-go's connecthttp package serves the Connect, gRPC, and gRPC-Web protocols from the same *connect.Server, so one set of handlers is reachable from all four.

See an example in action!

Why Vanguard?

  1. REST for RPC services: Add google.api.http annotations and your RPC handlers also serve REST clients. This is especially handy during a migration from a REST API to a schema-driven RPC API: existing REST clients keep working while your server implementations move to Protobuf and RPC.

  2. No extra code generation: Unlike gRPC-Gateway, Vanguard runs inside your Go server and needs no generated gateway code. It works from Protobuf descriptors at runtime, so service definitions can come from configuration, schema registries, or gRPC Server Reflection. That makes it a good fit for proxies, which don't need to be recompiled and redeployed each time an RPC service schema changes.

  3. RPC clients for REST servers: The same annotations let generated Connect clients call REST APIs. Teams can adopt RPC, for example in web or mobile clients, before every backend service has migrated.

  4. Existing gRPC services: vanguardgrpc registers grpc-go service implementations on a *connect.Server. connecthttp then serves them to Connect and gRPC-Web clients and Vanguard serves them over REST, without rewriting your handlers.

Usage

Vanguard builds on connect-go v2. Services register with a *connect.Server, and transports expose the server on the wire. The connecthttp package (part of connect-go) serves the Connect, gRPC, and gRPC-Web protocols. vanguard adds the REST half, driven by the google.api.http annotations on your service's Protobuf schema.

Serving REST

Register your services with a *connect.Server, then mount vanguard on an http.ServeMux alongside connecthttp:

server := connect.NewServer()
pingv1connect.RegisterPingServiceHandler(server, &pingServer{})

mux := http.NewServeMux()
connecthttp.Mount(mux, server) // Connect, gRPC, gRPC-Web
if err := vanguard.Mount(mux, server); err != nil { // google.api.http
	log.Fatal(err)
}
log.Fatal(http.ListenAndServe(":8080", mux))

Methods whose descriptors carry a google.api.http annotation become REST endpoints. Methods without one are only reachable via the RPC protocols. For services that don't define the mapping in their Protobuf sources, supply rules externally with vanguard.WithRules.

vanguard installs one catch-all "/" handler rather than per-pattern routes: google.api.http templates support **, single-segment *, and :verb suffixes that net/http's pattern matcher does not. Mount vanguard on a sub-mux (e.g. mux.Handle("/api/", subMux)) to scope its catch-all.

Dispatch flows through connect.Server.Call, so interceptors registered on the server fire for REST requests just like for RPC requests.

Calling REST servers

vanguard.NewTransport returns a connect.Transport that translates each RPC into the REST request described by the method's google.api.http annotation. Generated Connect clients work unchanged:

transport, err := vanguard.NewTransport(http.DefaultClient, "https://api.example.com")
if err != nil {
	log.Fatal(err)
}
client := pingv1connect.NewPingServiceClient(connect.NewClient(transport))
resp, err := client.Ping(ctx, &pingv1.PingRequest{Number: 42})
Proxying

vanguard.ForwardService registers methods that relay each call to an upstream *connect.Client, so you can put REST in front of a backend without its generated code. Only the service descriptor is needed:

upstream := connect.NewClient(connecthttp.NewTransport(http.DefaultClient, backendURL))
server := connect.NewServer()
server.Register(vanguard.ForwardService(upstream, serviceDescriptor)...)

mux := http.NewServeMux()
if err := vanguard.Mount(mux, server); err != nil {
	log.Fatal(err)
}

See the proxy example.

gRPC Handlers

The generated Go code for gRPC does not include a handler factory like Connect uses. Its generated functions instead register handler information with a grpc.ServiceRegistrar. The vanguardgrpc package provides a registrar that adapts those stubs onto a *connect.Server:

server := connect.NewServer()
registrar := vanguardgrpc.NewServiceRegistrar(server)

// Existing protoc-gen-go-grpc-generated code:
pingv1grpc.RegisterPingServiceServer(registrar, &pingServer{})

mux := http.NewServeMux()
connecthttp.Mount(mux, server) // Connect, gRPC, gRPC-Web
if err := vanguard.Mount(mux, server); err != nil { // google.api.http
	log.Fatal(err)
}

Status: Alpha

Vanguard is undergoing initial development and is not yet stable.

Offered under the Apache 2 license.

Image 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

Constants

This section is empty.

Variables

This section is empty.

Functions

func Forward added in v0.5.0

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

func Mount(mux connecthttp.ServeMux, server *connect.Server, opts ...Option) error

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

func WithDiscardUnknownQueryParams(discard bool) Option

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

func WithMaxReadBytes(n int64) Option

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

func WithSendCompression(name string) Option

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.

Image 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.

Jump to

Keyboard shortcuts

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