### Connect RPC Handler Example Source: https://pkg.go.dev/connectrpc.com/connect Illustrates setting up a handler for Connect RPC. This example shows an empty output. ```go Output: ``` -------------------------------- ### Example Output for Server.Client Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 This is an example output demonstrating a successful HTTP request handled by the in-memory server. ```text 200 OK ``` -------------------------------- ### Example Output for Server.Shutdown Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 This is an example output indicating that the server has been successfully shut down. ```text Server has shut down ``` -------------------------------- ### Example Unary RPC Output Source: https://pkg.go.dev/connectrpc.com/connect This example demonstrates the typical output format for a successful unary RPC call, showing the called method, request details, and the response. ```text calling: /connect.ping.v1.PingService/Ping request: number:42 response: number:42 ``` -------------------------------- ### Connect RPC Client Example Source: https://pkg.go.dev/connectrpc.com/connect Demonstrates how to make a client request in Connect RPC. The output shows a numeric response. ```go response: number:42 ``` -------------------------------- ### Get Peer Information from BidiStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Retrieves a description of the server for the RPC. ```go func (b *BidiStreamForClient[_, _]) Peer() Peer ``` -------------------------------- ### Get RPC Specification from BidiStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the specification for the RPC. ```go func (b *BidiStreamForClient[_, _]) Spec() Spec ``` -------------------------------- ### Get RPC Specification from BidiStream Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the specification for the RPC. ```go func (b *BidiStream[_, _]) Spec() Spec ``` -------------------------------- ### Get the Server's URL Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Returns the URL of the in-memory server. ```go func (s *Server) URL() string ``` -------------------------------- ### Configure buf.gen.yaml for Connect Go Source: https://pkg.go.dev/connectrpc.com/connect/cmd/protoc-gen-connect-go Configure your buf.gen.yaml file to include protoc-gen-go and protoc-gen-connect-go plugins. This setup generates both Go types and Connect service definitions. ```yaml version: v2 plugins: - local: protoc-gen-go out: gen - local: protoc-gen-connect-go out: gen ``` -------------------------------- ### Implementing a Connect RPC Server in Go Source: https://pkg.go.dev/connectrpc.com/connect This Go code defines a simple Ping server handler and sets up an HTTP server to listen for requests. It includes basic request handling and server configuration, with an example of using Protovalidate for request validation. ```go package main import ( "context" "log" "net/http" "connectrpc.com/connect" pingv1 "connectrpc.com/connect/internal/gen/connect/ping/v1" "connectrpc.com/connect/internal/gen/simple/connect/ping/v1/pingv1connect" "connectrpc.com/validate" ) type PingServer struct { pingv1connect.UnimplementedPingServiceHandler // returns errors from all methods } func (ps *PingServer) Ping(ctx context.Context, req *pingv1.PingRequest) (*pingv1.PingResponse, error) { return &pingv1.PingResponse{ Number: req.Number, }, nil } func main() { mux := http.NewServeMux() // The generated constructors return a path and a plain net/http // handler. mux.Handle( pingv1connect.NewPingServiceHandler( &PingServer{}, // Validation via Protovalidate is almost always recommended connect.WithInterceptors(validate.NewInterceptor()), ), ) p := new(http.Protocols) p.SetHTTP1(true) // For gRPC clients, it's convenient to support HTTP/2 without TLS. p.SetUnencryptedHTTP2(true) s := &http.Server{ Addr: "localhost:8080", Handler: mux, Protocols: p, } if err := s.ListenAndServe(); err != nil { log.Fatalf("listen failed: %v", err) } } ``` -------------------------------- ### WithHTTPGet Source: https://pkg.go.dev/connectrpc.com/connect Allows Connect-protocol clients to use HTTP GET requests for side-effect free unary RPC calls. Typically, the service schema indicates which procedures are idempotent (see WithIdempotency for an example protobuf schema). The gRPC and gRPC-Web protocols are POST-only, so this option has no effect when combined with WithGRPC or WithGRPCWeb. Using HTTP GET requests makes it easier to take advantage of CDNs, caching reverse proxies, and browsers' built-in caching. Note, however, that servers don't automatically set any cache headers; you can set cache headers using interceptors or by adding headers in individual procedure implementations. By default, all requests are made as HTTP POSTs. ```APIDOC ## WithHTTPGet ### Description Allows Connect-protocol clients to use HTTP GET requests for side-effect free unary RPC calls. Typically, the service schema indicates which procedures are idempotent (see WithIdempotency for an example protobuf schema). The gRPC and gRPC-Web protocols are POST-only, so this option has no effect when combined with WithGRPC or WithGRPCWeb. Using HTTP GET requests makes it easier to take advantage of CDNs, caching reverse proxies, and browsers' built-in caching. Note, however, that servers don't automatically set any cache headers; you can set cache headers using interceptors or by adding headers in individual procedure implementations. By default, all requests are made as HTTP POSTs. ### Method `WithHTTPGet` ### Returns - `ClientOption` - A client option that enables HTTP GET requests for unary calls. ``` -------------------------------- ### Get BidiStreamForClientSimple Specification Source: https://pkg.go.dev/connectrpc.com/connect Returns the specification for the RPC. This method is part of the BidiStreamForClientSimple interface. ```go func (b *BidiStreamForClientSimple[_, _]) Spec() Spec ``` -------------------------------- ### Get RPC specification for a Request Source: https://pkg.go.dev/connectrpc.com/connect Spec returns a description of this RPC, including its method and protocol details. ```go func (r *Request[_]) Spec() Spec ``` -------------------------------- ### NewImportServiceClient Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/generics/connect/import/v1/importv1connect Constructs a client for the connect.import.v1.ImportService service. By default, it uses the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, and sends uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the connect.WithGRPC() or connect.WithGRPCWeb() options. The URL supplied here should be the base URL for the Connect or gRPC server (for example, http://api.acme.com or https://acme.com/grpc). ```APIDOC ## func NewImportServiceClient ### Signature ```go func NewImportServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) ImportServiceClient ``` ### Description NewImportServiceClient constructs a client for the connect.import.v1.ImportService service. By default, it uses the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, and sends uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the connect.WithGRPC() or connect.WithGRPCWeb() options. The URL supplied here should be the base URL for the Connect or gRPC server (for example, http://api.acme.com or https://acme.com/grpc). ``` -------------------------------- ### Set Max URL Size for HTTP GET Requests Source: https://pkg.go.dev/connectrpc.com/connect Use WithHTTPGetMaxURLSize to limit the maximum URL length for Connect protocol GET requests. If the URL exceeds this limit, the request can either be sent as POST (if fallback is true) or fail with CodeResourceExhausted (if fallback is false). Defaults to no limit. ```go func WithHTTPGetMaxURLSize(bytes int, fallback bool) ClientOption ``` -------------------------------- ### Get HTTP trailers for a Response Source: https://pkg.go.dev/connectrpc.com/connect Trailer returns the trailers for this response. Connect- and Grpc- prefixed trailers are reserved and should not be written. ```go func (r *Response[_]) Trailer() http.Header ``` -------------------------------- ### Get BidiStreamForClientSimple Peer Information Source: https://pkg.go.dev/connectrpc.com/connect Retrieves information about the server for the RPC. This method is part of the BidiStreamForClientSimple interface. ```go func (b *BidiStreamForClientSimple[_, _]) Peer() Peer ``` -------------------------------- ### Get BidiStreamForClientSimple Response Trailer Source: https://pkg.go.dev/connectrpc.com/connect Returns the trailers received from the server. Trailers are not fully populated until Receive() returns an error wrapping io.EOF. ```go func (b *BidiStreamForClientSimple[Req, Res]) ResponseTrailer() http.Header ``` -------------------------------- ### Get Response Trailers from BidiStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the trailers received from the server. Trailers are not fully populated until Receive() returns an error wrapping io.EOF. ```go func (b *BidiStreamForClient[Req, Res]) ResponseTrailer() http.Header ``` -------------------------------- ### Implementing a Connect RPC Client in Go Source: https://pkg.go.dev/connectrpc.com/connect This Go code demonstrates how to create a Connect client to interact with a server. It shows how to instantiate the client and make a basic RPC call, handling the response and potential errors. ```go package main import ( "context" "log" "net/http" pingv1 "connectrpc.com/connect/internal/gen/connect/ping/v1" "connectrpc.com/connect/internal/gen/simple/connect/ping/v1/pingv1connect" ) func main() { client := pingv1connect.NewPingServiceClient( http.DefaultClient, "http://localhost:8080/", ) req := &pingv1.PingRequest{Number: 42} res, err := client.Ping(context.Background(), req) if err != nil { log.Fatalln(err) } log.Println(res) } ``` -------------------------------- ### Get an http.Client for the Server Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Returns an http.Client configured to use the server's in-memory pipes and speak HTTP/2. The client shares the same transport for its lifetime and its idle connections are closed when the server is closed. ```go func (s *Server) Client() *http.Client ``` -------------------------------- ### Construct New Client Source: https://pkg.go.dev/connectrpc.com/connect Initializes a new Client instance for a given HTTP client, URL, and optional configuration. Use ClientOption to customize protocol (gRPC, gRPC-Web), codec, compression, etc. ```go func NewClient[Req, Res any](httpClient HTTPClient, url string, options ...ClientOption) *Client[Req, Res] ``` -------------------------------- ### Create a new Server Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Creates a new in-memory server using the provided http.Handler. Configuration options can be passed to customize the server's behavior. ```go func NewServer(handler http.Handler, opts ...Option) *Server ``` -------------------------------- ### Enable HTTP GET for Unary Calls Source: https://pkg.go.dev/connectrpc.com/connect WithHTTPGet allows Connect-protocol clients to use HTTP GET for side-effect free unary RPC calls. This option has no effect with gRPC or gRPC-Web protocols. By default, all requests are made as HTTP POSTs. ```go func WithHTTPGet() ClientOption ``` -------------------------------- ### Client Initialization Source: https://pkg.go.dev/connectrpc.com/connect Initialize a new Connect-Go client for making RPC calls. You can configure the client with various options. ```APIDOC ## NewClient ### Description Creates a new client for making RPC calls to a specified URL. ### Signature func NewClient[Req, Res any](httpClient HTTPClient, url string, options ...ClientOption) *Client[Req, Res] ### Parameters - `httpClient` (HTTPClient): The HTTP client to use for making requests. - `url` (string): The base URL of the Connect RPC service. - `options` (...ClientOption): Optional configurations for the client. ``` -------------------------------- ### Get Response Trailers from BidiStream Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the response trailers. Handlers can write to trailers before returning. Avoid using trailers reserved for Connect and gRPC protocols. ```go func (b *BidiStream[Req, Res]) ResponseTrailer() http.Header ``` -------------------------------- ### Generate Connect Go Code with Protoc Source: https://pkg.go.dev/connectrpc.com/connect/cmd/protoc-gen-connect-go Use this command to generate base Go types and Connect code from a proto file. Ensure protoc-gen-connect-go is in your PATH. ```bash protoc --go_out=gen --connect-go_out=gen path/to/file.proto ``` -------------------------------- ### Get Error Detail Bytes Source: https://pkg.go.dev/connectrpc.com/connect Returns a copy of the Protobuf-serialized error detail. ```go func (d *ErrorDetail) Bytes() []byte ``` -------------------------------- ### NewImportServiceClient Function Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/generics/connect/import/v1/importv1connect Constructs a client for the connect.import.v1.ImportService. Defaults to Connect protocol with binary Protobuf Codec, gzipped responses, and uncompressed requests. Use connect.WithGRPC() or connect.WithGRPCWeb() for other protocols. The baseURL should be the server's base URL. ```go func NewImportServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) ImportServiceClient ``` -------------------------------- ### WithHTTPGetMaxURLSize Source: https://pkg.go.dev/connectrpc.com/connect Sets the maximum allowable URL length for GET requests made using the Connect protocol. If fallback is true and the URL exceeds this limit, the request will be sent as an HTTP POST. Otherwise, it fails with CodeResourceExhausted. ```APIDOC ## WithHTTPGetMaxURLSize ### Description Sets the maximum allowable URL length for GET requests made using the Connect protocol. It has no effect on gRPC or gRPC-Web clients, since those protocols are POST-only. If fallback is set to true and the URL would be longer than the configured maximum value, the request will be sent as an HTTP POST instead. If fallback is set to false, the request will fail with CodeResourceExhausted. ### Signature ```go func WithHTTPGetMaxURLSize(bytes int, fallback bool) ClientOption ``` ``` -------------------------------- ### Get Request Headers from BidiStream Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the headers received from the client for a bidirectional stream. ```go func (b *BidiStream[Req, Res]) RequestHeader() http.Header ``` -------------------------------- ### Create a Test HTTP Server with memhttp.NewServer Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp/memhttptest Use NewServer to construct a memhttp.Server suitable for tests. It logs runtime errors to testing.TB and automatically shuts down when the test completes. Startup and shutdown errors will fail the test. Customize with memhttp.Option, such as memhttp.WithCleanupTimeout. ```go func NewServer(tb testing.TB, handler http.Handler, opts ...memhttp.Option) *memhttp.Server ``` -------------------------------- ### Get Peer Information Source: https://pkg.go.dev/connectrpc.com/connect Retrieves information about the client connected to this RPC via the BidiStream. ```go func (b *BidiStream[_, _]) Peer() Peer ``` -------------------------------- ### NewPingServiceClient Constructor Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/generics/connect/ping/v1/pingv1connect Constructs a PingServiceClient. Defaults to Connect protocol with binary Protobuf Codec, gzipped responses, and uncompressed requests. Use connect.WithGRPC() or connect.WithGRPCWeb() for other protocols. The baseURL should be the server's base URL. ```go func NewPingServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) PingServiceClient ``` -------------------------------- ### Configure gRPC-Web Protocol Source: https://pkg.go.dev/connectrpc.com/connect WithGRPCWeb configures clients to use the gRPC-Web protocol. ```go func WithGRPCWeb() ClientOption ``` -------------------------------- ### Get Peer information for a Request Source: https://pkg.go.dev/connectrpc.com/connect Peer describes the other party for this RPC, providing details about the connection. ```go func (r *Request[_]) Peer() Peer ``` -------------------------------- ### Peer for ClientStreamForClientSimple Source: https://pkg.go.dev/connectrpc.com/connect Describes the server for the RPC. ```go func (c *ClientStreamForClientSimple[_, _]) Peer() Peer ``` -------------------------------- ### Get Error Detail Type Source: https://pkg.go.dev/connectrpc.com/connect Returns the fully-qualified name of the error detail's Protobuf message. ```go func (d *ErrorDetail) Type() string ``` -------------------------------- ### Create Server Streaming Handler (Simple) Source: https://pkg.go.dev/connectrpc.com/connect Constructs a Handler for a server streaming procedure using a simplified function signature. This option omits the Request wrapper and uses context.Context for header propagation. ```go func NewServerStreamHandlerSimple[Req, Res any]( procedure string, implementation func(context.Context, *Req, *ServerStream[Res]) error, options ...HandlerOption, ) *Handler ``` -------------------------------- ### Get CallInfo from Handler Context Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the `CallInfo` associated with a handler (incoming) context, if one exists. ```APIDOC ## CallInfoForHandlerContext ### Description CallInfoForHandlerContext returns the CallInfo for the given handler (i.e. incoming) context, if there is one. ### Signature ```go func CallInfoForHandlerContext(ctx context.Context) (CallInfo, bool) ``` ``` -------------------------------- ### Module Version Source: https://pkg.go.dev/connectrpc.com/connect Constant exposing the semantic version of the Connect module. ```go const Version = "1.19.2" ``` -------------------------------- ### Get Underlying Streaming Handler Connection Source: https://pkg.go.dev/connectrpc.com/connect Exposes the StreamingHandlerConn for a BidiStream, useful for wrapping the connection with alternative APIs. ```go func (b *BidiStream[Req, Res]) Conn() StreamingHandlerConn ``` -------------------------------- ### Peer for ClientStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Describes the server for the RPC. ```go func (c *ClientStreamForClient[_, _]) Peer() Peer ``` -------------------------------- ### Get Error - ServerStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Returns the first non-EOF error encountered during message reception. This should be checked after Receive returns false. ```go func (s *ServerStreamForClient[Res]) Err() error ``` -------------------------------- ### Compose Multiple Options Source: https://pkg.go.dev/connectrpc.com/connect Use WithOptions to combine multiple Option configurations into a single Option. ```go func WithOptions(options ...Option) Option ``` -------------------------------- ### Configure Client to Send Compressed Requests Source: https://pkg.go.dev/connectrpc.com/connect Use WithSendCompression to specify an algorithm for compressing request messages. If the algorithm is not registered, the client will return errors at runtime. Clients default to sending uncompressed requests as not all servers support compression. ```go func WithSendCompression(name string) ClientOption ``` -------------------------------- ### Get BidiStreamForClientSimple Response Header Source: https://pkg.go.dev/connectrpc.com/connect Returns the headers received from the server. This method blocks until the first call to Receive returns. ```go func (b *BidiStreamForClientSimple[Req, Res]) ResponseHeader() http.Header ``` -------------------------------- ### Configure Client Compression Source: https://pkg.go.dev/connectrpc.com/connect WithAcceptCompression makes a compression algorithm available to a client. Clients ask servers to compress responses using registered algorithms. Use WithSendCompression to compress requests. ```go func WithAcceptCompression( name string, newDecompressor func() Decompressor, newCompressor func() Compressor, ) ClientOption ``` -------------------------------- ### Serve HTTP Request Source: https://pkg.go.dev/connectrpc.com/connect Implements the http.Handler interface for the Handler. ```go func (h *Handler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) ``` -------------------------------- ### Get Response Headers from BidiStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the headers received from the server. This method blocks until the first call to Receive returns. ```go func (b *BidiStreamForClient[Req, Res]) ResponseHeader() http.Header ``` -------------------------------- ### Get underlying StreamingHandlerConn from ServerStream Source: https://pkg.go.dev/connectrpc.com/connect Conn exposes the underlying StreamingHandlerConn, which may be useful for wrapping the connection in a different high-level API. ```go func (s *ServerStream[Res]) Conn() StreamingHandlerConn ``` -------------------------------- ### Get HTTP headers for a Response Source: https://pkg.go.dev/connectrpc.com/connect Header returns the HTTP headers for this response. Connect- and Grpc- prefixed headers are reserved and should not be written. ```go func (r *Response[_]) Header() http.Header ``` -------------------------------- ### Configure Compression Source: https://pkg.go.dev/connectrpc.com/connect Configures handlers to support a compression algorithm for requests and/or responses. The provided constructors must produce compressors and decompressors for the same algorithm. Defaults to gzip. ```go func WithCompression( name string, newDecompressor func() Decompressor, newCompressor func() Compressor, ) HandlerOption ``` -------------------------------- ### Get concrete response message as any Source: https://pkg.go.dev/connectrpc.com/connect Any returns the concrete response message as an empty interface, ensuring *Response implements the AnyResponse interface. ```go func (r *Response[_]) Any() any ``` -------------------------------- ### Get HTTP headers for a Request Source: https://pkg.go.dev/connectrpc.com/connect Header returns the HTTP headers for this request. Connect- and Grpc- prefixed headers are reserved and should not be written. ```go func (r *Request[_]) Header() http.Header ``` -------------------------------- ### Create Simple Client Streaming Handler Source: https://pkg.go.dev/connectrpc.com/connect Constructs a Handler for a request-streaming procedure using the 'simple' generation option, which eliminates the Response wrapper. ```go func NewClientStreamHandlerSimple[Req, Res any]( procedure string, implementation func(context.Context, *ClientStream[Req]) (*Res, error), opions ...HandlerOption, ) *Handler ``` -------------------------------- ### WithClientOptions Source: https://pkg.go.dev/connectrpc.com/connect Composes multiple ClientOptions into one. ```APIDOC ## WithClientOptions ### Description Composes multiple ClientOptions into one. ### Method `WithClientOptions` ### Parameters - `options` (...ClientOption) - A variadic list of ClientOption to compose. ### Returns - `ClientOption` - A single ClientOption that combines the provided options. ``` -------------------------------- ### Get concrete request message as any Source: https://pkg.go.dev/connectrpc.com/connect Any returns the concrete request message as an empty interface, ensuring *Request implements the AnyRequest interface. ```go func (r *Request[_]) Any() any ``` -------------------------------- ### NewNotModifiedError Source: https://pkg.go.dev/connectrpc.com/connect Creates a Connect error indicating that a resource has not changed (304 Not Modified). This is primarily for HTTP GET requests with conditional headers. ```APIDOC ## func NewNotModifiedError ### Description NewNotModifiedError indicates that the requested resource hasn't changed. It should be used only when handlers wish to respond to conditional HTTP GET requests with a 304 Not Modified. In all other circumstances, including all RPCs using the gRPC or gRPC-Web protocols, it's equivalent to sending an error with CodeUnknown. The supplied headers should include Etag, Cache-Control, or any other headers required by RFC 9110 ยง 15.4.5. Clients should check for this error using IsNotModifiedError. ### Signature ```go func NewNotModifiedError(headers http.Header) *Error ``` ``` -------------------------------- ### NewServer Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp/memhttptest Constructs a memhttp.Server suitable for tests. It logs runtime errors to the provided testing.TB and automatically shuts down the server when the test completes. Startup and shutdown errors will fail the test. Use memhttp.Option to customize. ```APIDOC ## func NewServer ### Description NewServer constructs a memhttp.Server with defaults suitable for tests: it logs runtime errors to the provided testing.TB, and it automatically shuts down the server when the test completes. Startup and shutdown errors fail the test. To customize the server, use any memhttp.Option. In particular, it may be necessary to customize the shutdown timeout with memhttp.WithCleanupTimeout. ### Signature ```go func NewServer(tb testing.TB, handler http.Handler, opts ...memhttp.Option) *memhttp.Server ``` ### Parameters #### Function Parameters - **tb** (testing.TB) - The testing.TB instance to log errors to. - **handler** (http.Handler) - The http.Handler to serve. - **opts** (...memhttp.Option) - Optional configurations for the server. ``` -------------------------------- ### Get Response Trailers - ServerStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Returns the trailers received from the server. Trailers are not fully populated until Receive() returns an error that wraps io.EOF. ```go func (s *ServerStreamForClient[Res]) ResponseTrailer() http.Header ``` -------------------------------- ### Get Most Recent Message - ServerStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Returns the most recently unmarshaled message received from the server stream. This message is available after a successful call to Receive. ```go func (s *ServerStreamForClient[Res]) Msg() *Res ``` -------------------------------- ### Making a Request with buf curl Source: https://pkg.go.dev/connectrpc.com/connect This command demonstrates how to use `buf curl` to interact with a gRPC-compatible API. It supports specifying the protocol and data payload. ```bash go install github.com/bufbuild/buf/cmd/buf@latest buf curl --protocol grpc \ --data '{"sentence": "I feel happy."}' \ https://demo.connectrpc.com/connectrpc.eliza.v1.ElizaService/Say ``` -------------------------------- ### NewPingServiceClient Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/simple/connect/ping/v1/pingv1connect Constructs a client for the connect.ping.v1.PingService service. Supports custom protocols and options. ```APIDOC ## NewPingServiceClient ### Description Constructs a client for the connect.ping.v1.PingService service. By default, it uses the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, and sends uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the connect.WithGRPC() or connect.WithGRPCWeb() options. The URL supplied here should be the base URL for the Connect or gRPC server (for example, http://api.acme.com or https://acme.com/grpc). ### Signature ```go func NewPingServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) PingServiceClient ``` ``` -------------------------------- ### Request.HTTPMethod Source: https://pkg.go.dev/connectrpc.com/connect HTTPMethod returns the HTTP method for this request. This is nearly always POST, but side-effect-free unary RPCs could be made via a GET. ```APIDOC ## func (*Request[_]) HTTPMethod ### Description HTTPMethod returns the HTTP method for this request. This is nearly always POST, but side-effect-free unary RPCs could be made via a GET. On a newly created request, via NewRequest, this will return the empty string until the actual request is actually sent and the HTTP method determined. This means that client interceptor functions will see the empty string until *after* they delegate to the handler they wrapped. It is even possible for this to return the empty string after such delegation, if the request was never actually sent to the server (and thus no determination ever made about the HTTP method). ### Signature ```go func (r *Request[_]) HTTPMethod() string ``` ``` -------------------------------- ### Get Connect Error Code from Error Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the Connect error code from an error. Returns `CodeUnknown` if the error does not wrap a Connect `Error`. ```go func CodeOf(err error) Code ``` -------------------------------- ### Compose Client Options Source: https://pkg.go.dev/connectrpc.com/connect WithClientOptions composes multiple ClientOptions into a single option. ```go func WithClientOptions(options ...ClientOption) ClientOption ``` -------------------------------- ### Get RPC Specification for Client Stream Source: https://pkg.go.dev/connectrpc.com/connect Spec returns the specification for the RPC associated with a ClientStream. This provides details about the RPC, such as its method and schema. ```go func (c *ClientStream[_]) Spec() Spec ``` -------------------------------- ### Initialize ErrorWriter Source: https://pkg.go.dev/connectrpc.com/connect Constructs an ErrorWriter, optionally configuring its behavior with Handler options. WithRequireConnectProtocolHeader asserts the presence of the Connect protocol header. ```go func NewErrorWriter(opts ...HandlerOption) *ErrorWriter ``` -------------------------------- ### Client Options Source: https://pkg.go.dev/connectrpc.com/connect Configuration options for customizing client behavior. ```APIDOC ## Client Options ### Description Options to configure the behavior of the Connect-Go client. ### Available Options - `WithGRPC()`: Use gRPC-web protocol. - `WithGRPCWeb()`: Use gRPC-web protocol. - `WithProtoJSON()`: Use Protocol Buffers JSON encoding. - `WithHTTPGet()`: Use HTTP GET for requests. - `WithHTTPGetMaxURLSize(bytes int, fallback bool)`: Configure maximum URL size for GET requests. - `WithSendCompression(name string)`: Enable sending compressed requests. - `WithAcceptCompression(name string, newDecompressor func() Decompressor, ...)`: Enable accepting compressed responses. - `WithSendGzip()`: Enable sending gzip compressed requests. - `WithClientOptions(options ...ClientOption)`: Apply multiple client options. - `WithResponseInitializer(initializer func(spec Spec, message any) error)`: Set a response initializer. ``` -------------------------------- ### Get Underlying Streaming Handler Connection Source: https://pkg.go.dev/connectrpc.com/connect Conn exposes the underlying StreamingHandlerConn for a ClientStream. This can be useful for wrapping the connection in a different high-level API. ```go func (c *ClientStream[Req]) Conn() StreamingHandlerConn ``` -------------------------------- ### Client Creation Source: https://pkg.go.dev/connectrpc.com/connect Constructs a new Connect RPC client for a specific procedure. It takes an HTTP client, the service URL, and optional configuration options. ```APIDOC ## NewClient ### Description Constructs a new Client. ### Signature ```go func NewClient[Req, Res any](httpClient HTTPClient, url string, options ...ClientOption) *Client[Req, Res] ``` ``` -------------------------------- ### Get CallInfo from Handler Context Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the CallInfo associated with an incoming handler context. Returns true if CallInfo is found, false otherwise. ```go func CallInfoForHandlerContext(ctx context.Context) (CallInfo, bool) ``` -------------------------------- ### Generate Connect Go Code into Same Package Source: https://pkg.go.dev/connectrpc.com/connect/cmd/protoc-gen-connect-go Configure buf.gen.yaml to generate Connect Go code into the same package as the base Go types by omitting the package_suffix option or setting it to an empty value. ```yaml version: v2 plugins: - local: protoc-gen-go out: gen - local: protoc-gen-connect-go out: gen opt: package_suffix ``` -------------------------------- ### WithAcceptCompression Source: https://pkg.go.dev/connectrpc.com/connect Makes a compression algorithm available to a client. Clients ask servers to compress responses using any of the registered algorithms. The first registered algorithm is treated as the least preferred, and the last registered algorithm is the most preferred. It's safe to use this option liberally: servers will ignore any compression algorithms they don't support. To compress requests, pair this option with WithSendCompression. To remove support for a previously-registered compression algorithm, use WithAcceptCompression with nil decompressor and compressor constructors. Clients accept gzipped responses by default, using a compressor backed by the standard library's gzip package with the default compression level. Use WithSendGzip to compress requests with gzip. Calling WithAcceptCompression with an empty name is a no-op. ```APIDOC ## WithAcceptCompression ### Description Makes a compression algorithm available to a client. Clients ask servers to compress responses using any of the registered algorithms. The first registered algorithm is treated as the least preferred, and the last registered algorithm is the most preferred. It's safe to use this option liberally: servers will ignore any compression algorithms they don't support. To compress requests, pair this option with WithSendCompression. To remove support for a previously-registered compression algorithm, use WithAcceptCompression with nil decompressor and compressor constructors. Clients accept gzipped responses by default, using a compressor backed by the standard library's gzip package with the default compression level. Use WithSendGzip to compress requests with gzip. Calling WithAcceptCompression with an empty name is a no-op. ### Method `WithAcceptCompression` ### Parameters - `name` (string) - The name of the compression algorithm. - `newDecompressor` (func() Decompressor) - A function that returns a new decompressor. - `newCompressor` (func() Compressor) - A function that returns a new compressor. ### Returns - `ClientOption` - A client option that registers the compression algorithm. ``` -------------------------------- ### Check for Not Modified Error Source: https://pkg.go.dev/connectrpc.com/connect Checks if an error indicates a 'Not Modified' status, typically returned for HTTP GET requests with unchanged resources. ```go func IsNotModifiedError(err error) bool ``` -------------------------------- ### String Method Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/connectext/grpc/status/v1 Returns a string representation of the Status. ```go func (x *Status) String() string ``` -------------------------------- ### Create a new Response wrapper Source: https://pkg.go.dev/connectrpc.com/connect NewResponse wraps a generated response message, preparing it for an RPC response. ```go func NewResponse[T any](message *T) *Response[T] ``` -------------------------------- ### Get the Server's http.Transport Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Returns a http.Transport configured for in-memory pipes and HTTP/2. Callers can reconfigure this transport without affecting other transports. ```go func (s *Server) Transport() *http.Transport ``` -------------------------------- ### WithOptions Source: https://pkg.go.dev/connectrpc.com/connect Composes multiple Options into a single Option. ```APIDOC ## WithOptions ### Description Composes multiple Options into one. ### Signature ```go func WithOptions(options ...Option) Option ``` ### Parameters * **options** ([]Option) - A variadic list of options to compose. ``` -------------------------------- ### Get Response Trailers - ServerStream Source: https://pkg.go.dev/connectrpc.com/connect Returns the response trailers for a server stream. Handlers can write to these before returning. Connect- and Grpc- prefixed trailers are reserved. ```go func (s *ServerStream[Res]) ResponseTrailer() http.Header ``` -------------------------------- ### ServeHTTP Source: https://pkg.go.dev/connectrpc.com/connect Implements the http.Handler interface for a Handler. ```APIDOC ## func (*Handler) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request) ServeHTTP implements http.Handler. ``` -------------------------------- ### Get response headers from ServerStream Source: https://pkg.go.dev/connectrpc.com/connect ResponseHeader returns the response headers, which are sent with the first call to Send. Connect- and Grpc- prefixed headers are reserved. ```go func (s *ServerStream[Res]) ResponseHeader() http.Header ``` -------------------------------- ### WithGRPCWeb Source: https://pkg.go.dev/connectrpc.com/connect Configures clients to use the gRPC-Web protocol. ```APIDOC ## WithGRPCWeb ### Description Configures clients to use the gRPC-Web protocol. ### Method `WithGRPCWeb` ### Returns - `ClientOption` - A client option that sets the protocol to gRPC-Web. ``` -------------------------------- ### Get HTTP method for a Request Source: https://pkg.go.dev/connectrpc.com/connect HTTPMethod returns the HTTP method for this request, typically POST. It may be an empty string if the request has not yet been sent. ```go func (r *Request[_]) HTTPMethod() string ``` -------------------------------- ### Get Request Headers from Client Stream Source: https://pkg.go.dev/connectrpc.com/connect RequestHeader returns the HTTP headers received from the client for a ClientStream. This can be used to inspect incoming request metadata. ```go func (c *ClientStream[Req]) RequestHeader() http.Header ``` -------------------------------- ### Create Client Streaming Handler Source: https://pkg.go.dev/connectrpc.com/connect Constructs a Handler for a client streaming RPC procedure. ```go func NewClientStreamHandler[Req, Res any]( procedure string, implementation func(context.Context, *ClientStream[Req]) (*Response[Res], error), opions ...HandlerOption, ) *Handler ``` -------------------------------- ### Configure Request Initializer Source: https://pkg.go.dev/connectrpc.com/connect Provides a function to initialize new request messages dynamically. This function is called on server receive to construct the message before unmarshaling. ```go func WithRequestInitializer(initializer func(spec Spec, message any) error) HandlerOption ``` -------------------------------- ### Get Peer Information for Client Stream Source: https://pkg.go.dev/connectrpc.com/connect Peer describes the client associated with the current RPC for a ClientStream. This method is useful for inspecting client details. ```go func (c *ClientStream[_]) Peer() Peer ``` -------------------------------- ### Equal asserts that two values are equal Source: https://pkg.go.dev/connectrpc.com/connect/internal/assert Use Equal to check if two values of any type are identical. It accepts optional configuration options. ```go func Equal[T any](tb testing.TB, got, want T, options ...Option) bool ``` -------------------------------- ### IsNotModifiedError Source: https://pkg.go.dev/connectrpc.com/connect Checks if an error indicates that the requested resource has not changed. This is true only if the server used NewNotModifiedError in response to a Connect-protocol RPC made with an HTTP GET. ```APIDOC ## IsNotModifiedError ### Description IsNotModifiedError checks whether the supplied error indicates that the requested resource hasn't changed. It only returns true if the server used NewNotModifiedError in response to a Connect-protocol RPC made with an HTTP GET. ### Signature ```go func IsNotModifiedError(err error) bool ``` ``` -------------------------------- ### ImportResponse String Method Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/connect/collide/v1 Returns a string representation of the ImportResponse. ```go func (x *ImportResponse) String() string ``` -------------------------------- ### Get the Server's HTTP/1.1 http.Transport Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Returns a http.Transport configured for in-memory pipes and HTTP/1.1. Callers can reconfigure this transport without affecting other transports. ```go func (s *Server) TransportHTTP1() *http.Transport ``` -------------------------------- ### Server Lifecycle and Operations Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Methods for creating, managing, and interacting with the memhttp Server. ```APIDOC ## Server ### Type: Server Server is a net/http server that uses in-memory pipes instead of TCP. By default, it supports http/2 via h2c. It otherwise uses the same configuration as the zero value of http.Server. ### Function: NewServer ```go func NewServer(handler http.Handler, opts ...Option) *Server ``` NewServer creates a new Server that uses the given handler. Configuration options may be provided via [Option]s. ### Method: Cleanup ```go func (s *Server) Cleanup() error ``` Cleanup calls shutdown with a background context set with the cleanup timeout. The default timeout duration is 5 seconds. ### Method: Client ```go func (s *Server) Client() *http.Client ``` Client returns an http.Client configured to use in-memory pipes rather than TCP and speak HTTP/2. Client is configured to use the same transport for the lifetime of the server, and its idle connections are automatically closed when the server is closed. ### Method: Close ```go func (s *Server) Close() error ``` Close closes the server's listener. It does not wait for connections to finish. ### Method: RegisterOnShutdown ```go func (s *Server) RegisterOnShutdown(f func()) ``` RegisterOnShutdown registers a function to call on Shutdown. See http.Server.RegisterOnShutdown for details. ### Method: Shutdown ```go func (s *Server) Shutdown(ctx context.Context) error ``` Shutdown gracefully shuts down the server, without interrupting any active connections. See http.Server.Shutdown for details. ### Method: Transport ```go func (s *Server) Transport() *http.Transport ``` Transport returns a http.Transport configured to use in-memory pipes rather than TCP and speak HTTP/2. Callers may reconfigure the returned transport without affecting other transports. ### Method: TransportHTTP1 ```go func (s *Server) TransportHTTP1() *http.Transport ``` TransportHTTP1 returns a http.Transport configured to use in-memory pipes rather than TCP and speak HTTP/1.1. Callers may reconfigure the returned transport without affecting other transports. ### Method: URL ```go func (s *Server) URL() string ``` URL returns the server's URL. ### Method: Wait ```go func (s *Server) Wait() error ``` Wait blocks until the server exits, then returns an error if not a http.ErrServerClosed error. ``` -------------------------------- ### Create Unary Handler (Simple) Source: https://pkg.go.dev/connectrpc.com/connect Constructs a Handler for a request-response procedure using a simplified function signature. This option omits Request and Response wrappers, using context.Context for header propagation. ```go func NewUnaryHandlerSimple[Req, Res any]( procedure string, unary func(context.Context, *Req) (*Res, error), options ...HandlerOption, ) *Handler ``` -------------------------------- ### Get Underlying Connection - ServerStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Exposes the underlying StreamingClientConn for a client's view of a server streaming RPC. This can be useful for wrapping the connection in a different high-level API. ```go func (s *ServerStreamForClient[Res]) Conn() (StreamingClientConn, error) ``` -------------------------------- ### Call Bidirectional Streaming Procedure (Simple) Source: https://pkg.go.dev/connectrpc.com/connect A simplified method for calling bidirectional streaming RPCs. Request headers are automatically transmitted when this method is called, using CallInfo from the context. Response headers and trailers are read from the same CallInfo object. ```go func (c *Client[Req, Res]) CallBidiStreamSimple(ctx context.Context) (*BidiStreamForClientSimple[Req, Res], error) ``` -------------------------------- ### Get Most Recent Message from Client Stream Source: https://pkg.go.dev/connectrpc.com/connect Msg returns the most recent message that was unmarshaled by a call to Receive on a ClientStream. This message is available after Receive successfully advances the stream. ```go func (c *ClientStream[Req]) Msg() *Req ``` -------------------------------- ### Configure gRPC Protocol Source: https://pkg.go.dev/connectrpc.com/connect WithGRPC configures clients to use the HTTP/2 gRPC protocol. ```go func WithGRPC() ClientOption ``` -------------------------------- ### Get Request Headers from BidiStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the request headers. Headers are sent with the first call to Send. Avoid using headers reserved for Connect and gRPC protocols. ```go func (b *BidiStreamForClient[Req, Res]) RequestHeader() http.Header ``` -------------------------------- ### Create Server Streaming Handler Source: https://pkg.go.dev/connectrpc.com/connect Constructs a Handler for a server streaming RPC procedure. ```go func NewServerStreamHandler[Req, Res any]( procedure string, implementation func(context.Context, *Request[Req], *ServerStream[Res]) error, opions ...HandlerOption, ) *Handler ``` -------------------------------- ### Get Response Headers from BidiStream Source: https://pkg.go.dev/connectrpc.com/connect Retrieves the response headers. Headers are sent with the first call to Send. Avoid using headers reserved for Connect and gRPC protocols. ```go func (b *BidiStream[Req, Res]) ResponseHeader() http.Header ``` -------------------------------- ### Server Options Source: https://pkg.go.dev/connectrpc.com/connect/internal/memhttp%40v1.19.2 Options to configure the memhttp Server, such as cleanup timeout and error logging. ```APIDOC ## Options ### Type: Option An Option configures a Server. ### Function: WithCleanupTimeout ```go func WithCleanupTimeout(d time.Duration) Option ``` WithCleanupTimeout customizes the default five-second timeout for the server's Cleanup method. ### Function: WithErrorLog ```go func WithErrorLog(l *log.Logger) Option ``` WithErrorLog sets http.Server.ErrorLog. ### Function: WithOptions ```go func WithOptions(opts ...Option) Option ``` WithOptions composes multiple Options into one. ``` -------------------------------- ### NewPingServiceHandler Function Signature Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/generics/connect/ping/v1/pingv1connect This function signature shows how to build an HTTP handler from a PingService implementation. It returns the mount path and the handler itself. ```go func NewPingServiceHandler(svc PingServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) ``` -------------------------------- ### Get Response Headers - ServerStreamForClient Source: https://pkg.go.dev/connectrpc.com/connect Returns the headers received from the server for a client's view of a server streaming RPC. This method blocks until the first call to Receive returns. ```go func (s *ServerStreamForClient[Res]) ResponseHeader() http.Header ``` -------------------------------- ### Get First Non-EOF Error from Client Stream Source: https://pkg.go.dev/connectrpc.com/connect Err returns the first non-EOF error encountered by Receive on a ClientStream. This method should be called after Receive returns false to check for any unexpected errors. ```go func (c *ClientStream[Req]) Err() error ``` -------------------------------- ### ProtoReflect Method Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/connectext/grpc/status/v1 Provides reflection capabilities for the Status message. ```go func (x *Status) ProtoReflect() protoreflect.Message ``` -------------------------------- ### Initialize Response Messages Dynamically Source: https://pkg.go.dev/connectrpc.com/connect WithResponseInitializer provides a function to dynamically initialize new response messages. This function is called when the client receives a message and can be used to construct the message to be unmarshaled into, potentially based on the RPC specification. ```go func WithResponseInitializer(initializer func(spec Spec, message any) error) ClientOption ``` -------------------------------- ### Protocol Names Source: https://pkg.go.dev/connectrpc.com/connect Constants representing the names of supported protocols: Connect, gRPC, and gRPC-Web. ```go const ( ProtocolConnect = "connect" ProtocolGRPC = "grpc" ProtocolGRPCWeb = "grpcweb" ) ``` -------------------------------- ### Protobuf Message Interface Methods Source: https://pkg.go.dev/connectrpc.com/connect/internal/gen/connect/ping/v1 Common methods for protobuf messages, including Descriptor, ProtoMessage, ProtoReflect, Reset, and String. ```go func (*CountUpResponse) Descriptor() ([]byte, []int) Deprecated: Use CountUpResponse.ProtoReflect.Descriptor instead. ``` ```go func (*CountUpResponse) ProtoMessage() ``` ```go func (x *CountUpResponse) ProtoReflect() protoreflect.Message ``` ```go func (x *CountUpResponse) Reset() ``` ```go func (x *CountUpResponse) String() string ``` ```go func (*CumSumRequest) Descriptor() ([]byte, []int) Deprecated: Use CumSumRequest.ProtoReflect.Descriptor instead. ``` ```go func (*CumSumRequest) ProtoMessage() ``` ```go func (x *CumSumRequest) ProtoReflect() protoreflect.Message ``` ```go func (x *CumSumRequest) Reset() ``` ```go func (x *CumSumRequest) String() string ``` ```go func (*CumSumResponse) Descriptor() ([]byte, []int) Deprecated: Use CumSumResponse.ProtoReflect.Descriptor instead. ``` ```go func (*CumSumResponse) ProtoMessage() ``` ```go func (x *CumSumResponse) ProtoReflect() protoreflect.Message ``` ```go func (x *CumSumResponse) Reset() ``` ```go func (x *CumSumResponse) String() string ``` ```go func (*FailRequest) Descriptor() ([]byte, []int) Deprecated: Use FailRequest.ProtoReflect.Descriptor instead. ``` ```go func (*FailRequest) ProtoMessage() ``` ```go func (x *FailRequest) ProtoReflect() protoreflect.Message ``` ```go func (x *FailRequest) Reset() ``` ```go func (x *FailRequest) String() string ``` ```go func (*FailResponse) Descriptor() ([]byte, []int) Deprecated: Use FailResponse.ProtoReflect.Descriptor instead. ``` ```go func (*FailResponse) ProtoMessage() ``` ```go func (x *FailResponse) ProtoReflect() protoreflect.Message ``` ```go func (x *FailResponse) Reset() ``` ```go func (x *FailResponse) String() string ``` ```go func (*PingRequest) Descriptor() ([]byte, []int) Deprecated: Use PingRequest.ProtoReflect.Descriptor instead. ``` ```go func (*PingRequest) ProtoMessage() ``` ```go func (x *PingRequest) ProtoReflect() protoreflect.Message ``` ```go func (x *PingRequest) Reset() ``` ```go func (x *PingRequest) String() string ``` -------------------------------- ### WithResponseInitializer Source: https://pkg.go.dev/connectrpc.com/connect Provides a function that initializes a new message, which may be used to dynamically construct response messages. It is called on client receives to construct the message to be unmarshaled into. ```APIDOC ## WithResponseInitializer ### Description Provides a function that initializes a new message. It may be used to dynamically construct response messages. It is called on client receives to construct the message to be unmarshaled into. The message will be a non nil pointer to the type created by the client. Use the Schema field of the Spec to determine the type of the message. ### Signature ```go func WithResponseInitializer(initializer func(spec Spec, message any) error) ClientOption ``` ``` -------------------------------- ### NewNotModifiedError Function Source: https://pkg.go.dev/connectrpc.com/connect Creates an Error indicating a '304 Not Modified' status, typically used for conditional HTTP GET requests. It requires an http.Header containing relevant caching information. Use only for specific HTTP scenarios; otherwise, it's equivalent to CodeUnknown. ```go func NewNotModifiedError(headers http.Header) *Error ``` -------------------------------- ### Register Codec Option Source: https://pkg.go.dev/connectrpc.com/connect Use WithCodec to register a serialization method (codec) with a client or handler. Handlers can support multiple codecs, while clients use a single one. Defaults include Protobuf and JSON. Custom codecs can override defaults, but care must be taken with protocol-specific messages. ```go func WithCodec(codec Codec) Option ```