rrpc

package module
v0.0.0-...-666aaf5 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 24 Imported by: ? modules, 0 packages

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.

README

RRPC

RRPC is a REST RPC framework. Services are defined once in .rrpc schema files; type-safe server and client code is generated for Go and TypeScript. The generated code is backed by a lightweight HTTP runtime that handles routing, error serialisation, path/query parameter decoding, and multipart form uploads.

Repository layout

One git repo, one Go module per directory, tied together with local replace directives (no flat rrpc-xxx naming anymore — that was a holdover from when each was its own separate repo).

Directory Go module Purpose
./ (root) github.com/netgarden/rrpc RRPC server runtime (this package)
def/ github.com/netgarden/rrpc/def .rrpc file lexer, parser, and AST
gen/ github.com/netgarden/rrpc/gen rrpc-gen CLI — orchestrates code generation
gen/go/ github.com/netgarden/rrpc/gen/go Go code generator
gen/ts/ github.com/netgarden/rrpc/gen/ts TypeScript code generator
test/ github.com/netgarden/rrpc/test Example application
ts/ (npm package) Vendored TypeScript runtime counterpart to the root Go runtime

Definition file format (.rrpc)

Each module is described in a .rrpc file. Multiple files can be composed with include.

Module header
name    = "files"
version = "0.0.1"

option go_package = "files"

include "common.rrpc"

go_package is required when generating Go code and sets the package declaration of the output files.

Structs

Structs define the input and output shapes of methods. Fields are typed; arrays ([]T), maps and optional fields are supported. # starts a comment that runs to the end of the line.

struct LoginRequest {
    username string
    password string
}

struct SearchResult {
    items    []string
    total    int
    hasMore  bool
}

struct Config {
    timeout  int
    @optional tag string      # optional field
}

Optional fields. Annotate a field with @optional (on the same line, or on the line above) to let it be absent on the wire. Any other field annotation is an error.

required @optional
Go scalar / struct T *T with omitempty (nil = unset, so ""/0/false can be sent explicitly)
Go slice / map []T / map[K]V unchanged type, with omitempty (nil = unset)
TypeScript name!: T name?: T
GET query param required absent key leaves the field unset

Primitive types

Type Go type TypeScript type
string string string
bool bool boolean
int int number
int8/16/32/64 int8 … number
uint … uint … number
float32/64 float32/64 number
byte byte number
bytes io.Reader / io.Writer string | Uint8Array

Arrays use [] prefix: []string, []int. Maps use map[KeyType]ValueType.

Services

A service groups related methods. Its HTTP base path defaults to the service name and can be overridden with @path. The old spelling @Path is still accepted (the parser reads it as @path), so existing definitions keep working.

@path("/auth")
service Auth {
    login(request LoginRequest) (LoginResponse)
    logout()
}
Methods

Methods define the HTTP verb, path, inputs, and output. Defaults: POST, path = method name.

service Example {

    @method("PUT")
    @path("/upload/{filename:string}")
    upload(data bytes)

    @method("PUT")
    @path("/uploadJSON/{filename:string}")
    @RequestContentType("application/json")
    uploadJSON(data bytes)

    @method("POST")
    @path("/uploadWithInfo")
    @RequestContentType("application/pdf")
    uploadWithInfo(info UploadInfo, data bytes)

    @method("GET")
    @path("/download/{filename:string}")
    download() bytes

    @method("GET")
    @path("/downloadPDF/{filename:string}")
    @ResponseContentType("application/pdf")
    downloadPDF() bytes

    @method("POST")
    @path("/search")
    search(query SearchRequest) (SearchResponse)

    @method("GET")
    @path("/echo")
    echo(params EchoRequest) (EchoResponse)

}

Method constraints

HTTP verb Allowed inputs
POST, PUT Single struct, single bytes, or struct + bytes (multipart)
GET, HEAD, DELETE Single struct (serialised as query params); bytes inputs are not allowed

A single bytes output is streamed; the handler receives an io.Writer to write into.

@RequestContentType/@ResponseContentType override the Content-Type a bytes method uses on the wire — see the "Request body encoding by method type" table below for the defaults they override. Each requires a matching bytes input/output; using either where there's nothing for it to apply to is a parse error.

  • @RequestContentType on a method with a single bytes input (uploadJSON above) changes the whole request's Content-Type: what the server requires, and what a Go/TS client sends.
  • @RequestContentType on a multipart method (uploadWithInfo above, struct + bytes) instead changes the bytes field's own part, inside the multipart body — the envelope's Content-Type must keep carrying the boundary (multipart/form-data; boundary=...) and is never affected by this annotation.
  • @ResponseContentType changes the default Content-Type a bytes-output method's response carries, when the handler hasn't already set one itself (it still can, at runtime, overriding the annotation's default — this is unchanged from how the plain bytes-output default already worked).
  • Both may be used on the same method if it has bytes on both sides (e.g. transform(data bytes) bytes) — they're independent, and can differ.

The Go client picks up @RequestContentType/@ResponseContentType automatically, the next time a consumer regenerates. The TS client also supports both, but ts/client.ts is meant to be copied by hand into each consumer's own tree (there is no npm package) — a consumer only gets this fix once it re-copies that file, not just by regenerating its own .ts client code.

Path parameters use {name:type} syntax:

Type Matches
string One path segment (no /)
path Any characters including /
Errors

Module-level errors carry a numeric code and an HTTP status. They are returned from service implementations and serialised automatically.

error AuthenticationError {
    code      = 1
    http_code = 401
    message   = "authentication failed"
}

error NotFoundError {
    code      = 2
    http_code = 404
    message   = "not found"
}

Generated Go: var ErrAuthenticationError = rrpc.RRPCError{Code: 1, ...}


Code generation

CLI — rrpc-gen
# Build
cd gen && go build ./cmd/rrpc-gen/

# Generate Go code
rrpc-gen --source path/to/module.rrpc --target ./output/dir --type go

# Generate TypeScript code
rrpc-gen --source path/to/module.rrpc --target ./output/dir --type ts

RRPC_DEVEL=true makes the generators load templates from the filesystem instead of the embedded FS — useful when editing templates.

Go output files

For a source file module.rrpc the generator writes four files into --target:

File Contents
module.gen.go Struct types, service interfaces, error variables
module_handler.gen.go HTTP server handler and generated Go client
rrpc.module.gen.go Module registration, SetXxxService methods
rrpc.client.gen.go Client struct, NewClient, SizedReader/Closer helpers

Never edit *.gen.go files directly — regenerate them with rrpc-gen.

TypeScript output

One .gen.ts file is produced per source. It exports a typed client class. Import it from $lib/<module> in SvelteKit.


Go — implementing a service

  1. Generate code from the .rrpc file.
  2. Create an impl/ subdirectory and implement the generated interface.
  3. Register the module in your server setup.
// modules/auth/impl/auth.go
package impl

import (
    "github.com/netgarden/rrpc"
    "github.com/netgarden/rrpc/test/modules/auth"
)

type AuthService struct{}

func (s *AuthService) Login(ctx *rrpc.Context, req *auth.LoginRequest) (*auth.LoginResponse, error) {
    if req.Username != req.Password {
        return nil, auth.ErrAuthenticationError
    }
    return &auth.LoginResponse{Ok: true}, nil
}

func (s *AuthService) Logout(ctx *rrpc.Context) error {
    return nil
}

Reading path params:

func (s *FilesService) Upload(ctx *rrpc.Context, r io.Reader) error {
    filename := ctx.Params().GetString("filename")
    // write r to disk as filename…
}

Bytes output — write to the provided io.Writer:

func (s *FilesService) Download(ctx *rrpc.Context, w io.Writer) error {
    filename := ctx.Params().GetString("filename")
    f, err := os.Open(filepath.Join(s.dir, filename))
    if err != nil { return err }
    defer f.Close()
    _, err = io.Copy(w, f)
    return err
}

Multipart (struct + bytes):

func (s *FilesService) Upload2(ctx *rrpc.Context, info *files.UploadDataInfo, r io.Reader) error {
    f, err := os.Create(filepath.Join(s.dir, info.Filename))
    if err != nil { return err }
    defer f.Close()
    _, err = io.Copy(f, r)
    return err
}
Server setup
authModule := auth.NewModule()
authModule.SetAuthService(impl.NewAuthService())

filesModule := files.NewModule()
filesModule.SetFilesService(impl.NewFilesService("uploads/"))

srv := rrpc.NewServer()
srv.RegisterModule(authModule)
srv.RegisterModule(filesModule)

// Optional: authentication / logging hook
srv.SetOnRequest(func(w http.ResponseWriter, r *http.Request) error {
    if r.Header.Get("Authorization") == "" {
        return rrpc.RRPCError{Code: 401, Name: "Unauthorized", Message: "missing token", HTTPStatus: 401}
    }
    return nil
})

http.ListenAndServe(":8080", srv)

To measure traffic (metrics, access logs) register a ResponseObserver. It is called once per request after the response is written, for every response the server produced: errors, requests that matched no route, and WebSocket upgrades (status 101, reported when the socket closes).

srv.Observe(func(r *http.Request, info rrpc.ResponseInfo) {
    // info.Route    the matched route's path template ("/hooks/{token:string}"), "" if none matched:
    //               safe as a metrics label, unlike r.URL.Path
    // info.Status   the HTTP status written (200 if none)
    // info.Bytes    response body bytes; info.Duration  time spent in ServeHTTP
})

Observers must not block. The server only wraps the ResponseWriter (to record status and size) when an observer is registered, and the wrapper still supports hijacking and flushing. Register observers before serving.

Routes are matched by specificity, not registration order: an exact/parameterized path always wins over a {name:path} catch-all that also matches the same request, and ties break deterministically. This means a catch-all service (e.g. serving a static UI build for any unmatched path) can safely be registered alongside specific API services in the same or a different module — it will never intermittently shadow a more specific route, regardless of which module or which entry in ServerModule.Services()'s map it happens to be.

Go client usage
client := auth.NewClient("http://localhost:8080")

resp, err := client.Auth.Login(ctx, &auth.LoginRequest{
    Username: "alice",
    Password: "secret",
})

// Files — path param passed as first argument after ctx
err = client.Files.Upload(ctx, "hello.txt", rrpc.NewSizedReader(fileReader, fileSize))

// Download — returns *SizedReadCloser
rc, err := client.Files.Download(ctx, "hello.txt")
defer rc.Close()
io.Copy(dst, rc)

// Multipart
err = client.Files.Upload2(ctx, &files.UploadDataInfo{Filename: "doc.pdf"}, rrpc.NewSizedReader(reader, size))

// GET with query params (struct fields become URL params automatically)
resp, err := client.Echo.Echo(ctx, &echo.EchoRequest{Message: "hi", Count: 3, Flag: true})

TypeScript / SvelteKit client

Generated .gen.ts files expose typed client classes. Use them from a +page.svelte or any .ts file.

import { FilesClient } from '$lib/files';
import { AuthClient } from '$lib/auth';
import { EchoClient } from '$lib/echo';

const auth  = new AuthClient('');      // empty = same origin
const files = new FilesClient('');
const echo  = new EchoClient('');

// POST with JSON body
const res = await auth.authService.login({ username: 'alice', password: 'secret' });

// PUT with raw bytes
const buf = await file.arrayBuffer();
await files.filesService.upload('hello.txt', new Uint8Array(buf));

// POST multipart (struct + bytes)
await files.filesService.upload2({ filename: 'doc.pdf' }, new Uint8Array(buf));

// GET with query params
const result = await echo.echoService.echo({ message: 'hi', count: 3, flag: true });

// GET with path param
const bytes = await files.filesService.download('hello.txt');
const text  = new TextDecoder().decode(bytes);

Errors thrown by the client are instances of RRPCError:

import { RRPCError } from '$lib/rrpc';

try {
    await auth.authService.login({ username: 'x', password: 'y' });
} catch (e) {
    if (e instanceof RRPCError) {
        console.log(e.code, e.error, e.message, e.cause);
    }
}

Error wire format

All errors are returned as application/problem+json:

{
  "error": "AuthenticationError",
  "code": 1,
  "msg": "authentication failed",
  "cause": "passwords do not match"
}

The HTTP status code is set from the error's http_code (module errors) or the framework's built-in codes.

Framework error codes
Code HTTP Name Meaning
0 400 RrpcEndpoint Handler returned a non-RRPCError
-1 400 RrpcRequestFailed HTTP request failed (client)
-2 404 RrpcBadRoute No handler matched the path
-3 405 RrpcBadMethod Wrong HTTP verb
-4 400 RrpcBadRequest Malformed request body or params
-5 500 RrpcBadResponse Failed to serialise the response
-6 500 RrpcServerPanic Unhandled panic in a handler
-7 500 RrpcInternalError Internal server error
-8 400 RrpcClientDisconnected Client disconnected mid-stream

Request body encoding by method type

Inputs HTTP verb Encoding
None any No body
Single struct POST / PUT JSON body (application/json)
Single bytes POST / PUT Raw binary body (application/octet-stream by default, or @RequestContentType's value)
Struct + bytes POST / PUT Multipart form data (envelope always multipart/form-data, boundary added at send time); struct as a named JSON field, bytes as a file field whose own part-level Content-Type is application/octet-stream by default, or @RequestContentType's value — the envelope itself is never affected by that annotation
Single struct GET URL query parameters (see below)
Single struct HEAD / DELETE JSON body, like POST — but the validator still requires primitive fields, as if they were query parameters

A bytes output's response Content-Type defaults to application/octet-stream, or @ResponseContentType's value; a handler may still override it at runtime by setting the header itself before writing, same as before this existed.

GET query parameters. The Go client (rrpc.EncodeQueryParams) and the TS client encode the request struct into the query string; the server decodes it with rrpc.DecodeQueryParams. Both use the struct's JSON names:

  • Each value is read according to its field's type, not its text: a string field receives 2024, true or 007 verbatim; a bool accepts true/false/1/0; numbers must parse as numbers. A value that doesn't fit its field is a 400.
  • Unset @optional fields and omitempty zero values are left out of the query.
  • A map[string]V field uses one level of bracket notation: filters[name]=foo.
  • Slices and deeper nesting have no query-string form (the validator rejects them for GET methods; EncodeQueryParams returns an error).

Static file serving

// In service implementation
handler := rrpc.NewStaticFilesHandler("filepath", os.DirFS("."), "web/build")

func (s *StaticService) Serve(ctx *rrpc.Context, w io.Writer) error {
    return handler.ServeStatic(ctx, w)
}

ServeStatic sets Content-Type from the file extension and returns 404 for paths outside the base directory.


Running tests

# rrpc runtime unit tests (uses generated testmodule)
make test

# rrpc-def parser tests
cd def && go test ./...

# rrpc-test integration (start the server)
cd test && go run ./cmd/server/

# rrpc-test web frontend
cd test/web && npm run dev

License

Apache License 2.0, see LICENSE.

Documentation

Index

Constants

View Source
const ContentTypeHeader = "Content-Type"
View Source
const MethodNameCtxKey = "rrpc-method"
View Source
const ServiceNameCtxKey = "rrpc-service"

Variables

View Source
var (
	ErrRrpcEndpoint           = RRPCError{Code: 0, Name: "RrpcEndpoint", Message: "endpoint error", HTTPStatus: 400}
	ErrRrpcRequestFailed      = RRPCError{Code: -1, Name: "RrpcRequestFailed", Message: "request failed", HTTPStatus: 400}
	ErrRrpcBadRoute           = RRPCError{Code: -2, Name: "RrpcBadRoute", Message: "bad route", HTTPStatus: 404}
	ErrRrpcBadMethod          = RRPCError{Code: -3, Name: "RrpcBadMethod", Message: "bad method", HTTPStatus: 405}
	ErrRrpcBadRequest         = RRPCError{Code: -4, Name: "RrpcBadRequest", Message: "bad request", HTTPStatus: 400}
	ErrRrpcBadResponse        = RRPCError{Code: -5, Name: "RrpcBadResponse", Message: "bad response", HTTPStatus: 500}
	ErrRrpcServerPanic        = RRPCError{Code: -6, Name: "RrpcServerPanic", Message: "server panic", HTTPStatus: 500}
	ErrRrpcInternalError      = RRPCError{Code: -7, Name: "RrpcInternalError", Message: "internal error", HTTPStatus: 500}
	ErrRrpcClientDisconnected = RRPCError{Code: -8, Name: "RrpcClientDisconnected", Message: "client disconnected", HTTPStatus: 400}
)

RRPC errors

View Source
var DataMethods = []string{"POST", "PUT"}

Functions

func DecodeQueryParams

func DecodeQueryParams(values url.Values, v interface{}) error

DecodeQueryParams decodes URL query parameters into a struct using JSON tags.

Each value is converted according to the type of the field it lands in, not by guessing from its text: a string field keeps "2024", "true" or "007" exactly as sent, a bool field accepts anything strconv.ParseBool does, and numeric fields parse as numbers. A value that doesn't parse as its field's type is passed through unconverted so the JSON decode reports it, which surfaces to the caller as an error (a 400 from generated handlers). Keys that match no field of v (or a v that isn't a struct pointer) fall back to guessing numeric/boolean values from their text.

Keys using bracket notation ("filters[name]=foo") are grouped into a nested map under the outer key ("filters": {"name": "foo"}) before unmarshaling — the encoding a map-typed field (e.g. a generated DatatableRequest.Filters map[string]string) arrives in, since a browser's URLSearchParams has no native nested-object representation. Only one level of nesting is supported (matching map[string]V fields); a key with more than one bracket pair (e.g. "a[b][c]") is not specially parsed.

func EncodeQueryParams

func EncodeQueryParams(v interface{}) (url.Values, error)

EncodeQueryParams is the inverse of DecodeQueryParams: it turns a struct (or pointer to one) into URL query parameters using its JSON tags, so a value survives the round trip through DecodeQueryParams unchanged.

Fields JSON would omit (nil pointers, omitempty zero values) and null values are left out. A map[string]V field (or a struct of scalars, which JSON cannot tell apart from a map) becomes one level of bracket notation ("filters[name]=foo"). []byte fields are sent as the base64 text JSON uses for them. Slices and anything nested deeper than one level have no query-string form and return an error instead of being silently mangled - the rrpc validator rejects such fields for GET methods for the same reason.

func EscapePathValue

func EscapePathValue(value string) string

EscapePathValue encodes value for safe inclusion in a URL path built from a "path"-typed parameter, which — unlike a "string"-typed one — may itself contain "/" separators that must be preserved rather than escaped away. Each segment between slashes is percent-encoded individually; the separators themselves are not.

func FormDataPartHeader

func FormDataPartHeader(fieldname, filename, contentType string) textproto.MIMEHeader

FormDataPartHeader returns the MIME header a multipart bytes field's part should carry: the same Content-Disposition mime/multipart.Writer. CreateFormFile builds internally, but with contentType instead of its hardcoded "application/octet-stream" default - for generated clients that need to declare that part's own Content-Type (see @RequestContentType on a multipart method). Pass it to (*multipart.Writer).CreatePart in place of CreateFormFile.

func NewResponseWriter

func NewResponseWriter(w http.ResponseWriter, contentType string) io.Writer

Types

type ClientRawRecvStream

type ClientRawRecvStream struct {
	io.Reader
	// contains filtered or unexported fields
}

func DialRawRecvStream

func DialRawRecvStream(ctx context.Context, url string, opts DialOptions) (*ClientRawRecvStream, error)

func (*ClientRawRecvStream) Close

func (d *ClientRawRecvStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*ClientRawRecvStream) CloseGracefully

func (d *ClientRawRecvStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*ClientRawRecvStream) Context

func (d *ClientRawRecvStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

type ClientRawSendStream

type ClientRawSendStream struct {
	io.Writer
	// contains filtered or unexported fields
}

func DialRawSendStream

func DialRawSendStream(ctx context.Context, url string, opts DialOptions) (*ClientRawSendStream, error)

func (*ClientRawSendStream) Close

func (d *ClientRawSendStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*ClientRawSendStream) CloseGracefully

func (d *ClientRawSendStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*ClientRawSendStream) Context

func (d *ClientRawSendStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

type ClientRawStream

type ClientRawStream struct {
	io.ReadWriter
	// contains filtered or unexported fields
}

ClientRawStream, ClientRawSendStream, ClientRawRecvStream are the dialing counterparts of RawStream/RawInStream/RawOutStream, used for streaming methods whose direction is declared "bytes" rather than a struct type.

func DialRawStream

func DialRawStream(ctx context.Context, url string, opts DialOptions) (*ClientRawStream, error)

func (*ClientRawStream) Close

func (d *ClientRawStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*ClientRawStream) CloseGracefully

func (d *ClientRawStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*ClientRawStream) Context

func (d *ClientRawStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

type ClientRecvStream

type ClientRecvStream[Out any] struct {
	// contains filtered or unexported fields
}

ClientRecvStream is the client side of "@OutputStream" - the client is the one receiving, so it only has Recv (with the same error-frame surfacing as ClientStream.Recv).

func DialRecvStream

func DialRecvStream[Out any](ctx context.Context, url string, opts DialOptions) (*ClientRecvStream[Out], error)

func (*ClientRecvStream) Close

func (d *ClientRecvStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*ClientRecvStream) CloseGracefully

func (d *ClientRecvStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*ClientRecvStream) Context

func (d *ClientRecvStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

func (*ClientRecvStream[Out]) Recv

func (s *ClientRecvStream[Out]) Recv() (Out, error)

type ClientSendStream

type ClientSendStream[In any] struct {
	// contains filtered or unexported fields
}

ClientSendStream is the client side of "@InputStream" - the client is the one sending, so it only has Send.

func DialSendStream

func DialSendStream[In any](ctx context.Context, url string, opts DialOptions) (*ClientSendStream[In], error)

func (*ClientSendStream) Close

func (d *ClientSendStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*ClientSendStream) CloseGracefully

func (d *ClientSendStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*ClientSendStream) Context

func (d *ClientSendStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

func (*ClientSendStream[In]) Send

func (s *ClientSendStream[In]) Send(msg In) error

type ClientStream

type ClientStream[In, Out any] struct {
	// contains filtered or unexported fields
}

ClientStream, ClientSendStream, ClientRecvStream are the generated Go client's counterparts of Stream/InStream/OutStream - used by one Go program calling another rrpc-based Go service directly (via the generated *ServiceClientHandler methods), independent of the browser/TS client. Type parameter naming stays consistent with the .rrpc declaration regardless of which side's code you're reading (In is always the client->server type, Out always server->client) - only the available method set flips between server (accepting an inbound connection) and client (dialing an outbound one).

func DialStream

func DialStream[In, Out any](ctx context.Context, url string, opts DialOptions) (*ClientStream[In, Out], error)

func (*ClientStream) Close

func (d *ClientStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*ClientStream) CloseGracefully

func (d *ClientStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*ClientStream) Context

func (d *ClientStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

func (*ClientStream[In, Out]) Recv

func (s *ClientStream[In, Out]) Recv() (Out, error)

Recv reads the next server->client frame. A received {"error": ...} envelope surfaces here as a returned Go error (built from the same RRPCError shape the server sends) - the natural Go equivalent of the TS client's message-iterator throwing on an error frame.

func (*ClientStream[In, Out]) Send

func (s *ClientStream[In, Out]) Send(msg In) error

type Context

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

func NewContext

func NewContext(request *http.Request, response http.ResponseWriter, params *Params) *Context

func (*Context) Get

func (c *Context) Get(key any) (any, bool)

func (*Context) Hijacked

func (c *Context) Hijacked() bool

Hijacked reports whether this request's response has already been handled by a WebSocket upgrade attempt (see Upgrade*/UpgradeRaw* in websocket.go) - true both when the upgrade succeeded and when it was attempted but failed, since the underlying WebSocket library writes its own response to Response() in either case. Once true, Response() is no longer usable for a normal HTTP response - the server will not attempt to write a JSON error body for whatever error the handler eventually returns.

func (*Context) IsHTTPS

func (c *Context) IsHTTPS() bool

func (*Context) Params

func (c *Context) Params() *Params

func (*Context) Request

func (c *Context) Request() *http.Request

func (*Context) Response

func (c *Context) Response() http.ResponseWriter

func (*Context) Set

func (c *Context) Set(key, value any)

type DialOptions

type DialOptions struct {
	Subprotocols []string
}

DialOptions configures a client-side streaming connection - the dialing counterpart of UpgradeOptions. Bare today; grows a token/subprotocol option later if/when the generated non-streaming Go client adopts one, rather than inventing one speculatively here.

type InStream

type InStream[In any] struct {
	// contains filtered or unexported fields
}

InStream is a client->server-only typed message stream - "@InputStream". The server only receives; there's no Send/SendError - no existing "client sends a typed error to the server" concept to extend.

func UpgradeInStream

func UpgradeInStream[In any](ctx *Context, opts UpgradeOptions) (*InStream[In], error)

func (*InStream) Close

func (d *InStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*InStream) CloseGracefully

func (d *InStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*InStream) Context

func (d *InStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

func (*InStream[In]) Recv

func (s *InStream[In]) Recv() (In, error)

type MethodHandlerFunc

type MethodHandlerFunc = func(ctx *Context) error

type MethodHolder

type MethodHolder struct {
	Path        *Path
	Type        string
	ContentType string
	HandlerFunc MethodHandlerFunc
}

type Middleware

type Middleware func(ctx *Context, next func(*Context) error) error

type OutStream

type OutStream[Out any] struct {
	// contains filtered or unexported fields
}

OutStream is a server->client-only typed message stream - "@OutputStream". The server only sends; it has no typed Recv, but can still observe disconnect via Context() cancellation.

func UpgradeOutStream

func UpgradeOutStream[Out any](ctx *Context, opts UpgradeOptions) (*OutStream[Out], error)

func (*OutStream) Close

func (d *OutStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*OutStream) CloseGracefully

func (d *OutStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*OutStream) Context

func (d *OutStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

func (*OutStream[Out]) Send

func (s *OutStream[Out]) Send(msg Out) error

func (*OutStream[Out]) SendError

func (s *OutStream[Out]) SendError(err error) error

type Params

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

func NewParams

func NewParams() *Params

func (*Params) GetString

func (p *Params) GetString(key string) string

func (*Params) SetString

func (p *Params) SetString(key string, value string)

type Path

type Path struct {
	Path   string
	Regex  string
	Params map[string]PathParam
}

func ParsePath

func ParsePath(path string) *Path

type PathParam

type PathParam struct {
	Name string
	Type string
}

type RRPCError

type RRPCError struct {
	Name       string `json:"error"`
	Code       int    `json:"code"`
	Message    string `json:"msg"`
	Cause      string `json:"cause,omitempty"`
	HTTPStatus int    `json:"-"`
	// contains filtered or unexported fields
}

func (RRPCError) Error

func (e RRPCError) Error() string

func (RRPCError) Is

func (e RRPCError) Is(target error) bool

func (RRPCError) Unwrap

func (e RRPCError) Unwrap() error

func (RRPCError) WithCause

func (e RRPCError) WithCause(cause error) RRPCError

func (RRPCError) WithCauseString

func (e RRPCError) WithCauseString() RRPCError

WithCauseString sets the cause from the Cause string field. Used after JSON unmarshaling to restore the error chain.

func (RRPCError) WithCausef

func (e RRPCError) WithCausef(format string, args ...interface{}) RRPCError

type RawInStream

type RawInStream struct {
	io.Reader
	// contains filtered or unexported fields
}

func UpgradeRawInStream

func UpgradeRawInStream(ctx *Context, opts UpgradeOptions) (*RawInStream, error)

func (*RawInStream) Close

func (d *RawInStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*RawInStream) CloseGracefully

func (d *RawInStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*RawInStream) Context

func (d *RawInStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

type RawOutStream

type RawOutStream struct {
	io.Writer
	// contains filtered or unexported fields
}

func UpgradeRawOutStream

func UpgradeRawOutStream(ctx *Context, opts UpgradeOptions) (*RawOutStream, error)

func (*RawOutStream) Close

func (d *RawOutStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*RawOutStream) CloseGracefully

func (d *RawOutStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*RawOutStream) Context

func (d *RawOutStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

type RawStream

type RawStream struct {
	io.ReadWriter
	// contains filtered or unexported fields
}

RawStream, RawInStream, RawOutStream are the raw-byte-stream counterparts of Stream/InStream/OutStream, generated instead of the typed generics above when a streaming method's direction is declared with "bytes" rather than a struct type. Each embeds the corresponding stdlib interface directly via websocket.NetConn (which already handles buffering/chunking across WebSocket frame boundaries), so it can be passed straight into io.Copy, wrapped in a bufio.Scanner, or handed to any other io.Reader/io.Writer-consuming code.

func UpgradeRawStream

func UpgradeRawStream(ctx *Context, opts UpgradeOptions) (*RawStream, error)

func (*RawStream) Close

func (d *RawStream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*RawStream) CloseGracefully

func (d *RawStream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*RawStream) Context

func (d *RawStream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

type ResponseInfo

type ResponseInfo struct {
	// Route is the matched route's path template (service path + method
	// path, e.g. "/hooks/{token}"), never the raw request path, so it is
	// safe as a metrics label. It is "" when no route matched.
	Route string
	// Status is the HTTP status written (200 if the handler wrote none).
	// For a hijacked (WebSocket) connection it is 101.
	Status int
	// Bytes is the number of response body bytes written.
	Bytes int64
	// Duration is the time spent in ServeHTTP.
	Duration time.Duration
}

ResponseInfo describes one finished request, as reported to a ResponseObserver. It covers every response the server produced, including error responses and requests that matched no route.

type ResponseObserver

type ResponseObserver func(r *http.Request, info ResponseInfo)

ResponseObserver is called once per request, after the response has been written. It must not block and must not touch the request's body or the ResponseWriter.

type Server

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

func NewServer

func NewServer() *Server

func (*Server) Observe

func (s *Server) Observe(observers ...ResponseObserver)

Observe registers a ResponseObserver. Not safe to call concurrently with serving; register observers before the server starts.

func (*Server) RegisterModule

func (s *Server) RegisterModule(module ServerModule) error

func (*Server) ServeHTTP

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

func (*Server) SetOnRequest

func (s *Server) SetOnRequest(fn func(w http.ResponseWriter, r *http.Request) error)

func (*Server) Use

func (s *Server) Use(middlewares ...Middleware)

type ServerModule

type ServerModule interface {
	Name() string
	Services() map[string]ServiceHandler
}

type ServiceHandler

type ServiceHandler interface {
	Name() string
	Path() *Path
	Methods() []MethodHolder
}

type StaticFilesHandler

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

func NewStaticFilesHandler

func NewStaticFilesHandler(pathParamName string, fs fs.FS, baseDir string) *StaticFilesHandler

func (*StaticFilesHandler) ServeStatic

func (h *StaticFilesHandler) ServeStatic(ctx *Context, w io.Writer) error

type Stream

type Stream[In, Out any] struct {
	// contains filtered or unexported fields
}

Stream is a bidirectional typed message stream - "@Stream".

func UpgradeStream

func UpgradeStream[In, Out any](ctx *Context, opts UpgradeOptions) (*Stream[In, Out], error)

func (*Stream) Close

func (d *Stream) Close(code websocket.StatusCode, reason string) error

Close closes the underlying connection. Safe to call multiple times.

func (*Stream) CloseGracefully

func (d *Stream) CloseGracefully() error

CloseGracefully closes the connection with a normal-closure status - the generated handler wrapper for every streaming method defers this once Upgrade succeeds, specifically so a handler that returns normally (all data sent, done) ends the connection with a proper WS close frame instead of leaving that to Context()'s fallback. That fallback (see Context's doc comment and upgrade's use of the request context) only exists to eventually reclaim a connection whose handler forgot to close it - it does so via CloseRead's background reader observing context cancellation, which lands on Conn's internal abrupt teardown, not a graceful close, and shows up client-side as a "closed abnormally" error even though every byte was already delivered. Safe to call multiple times, same as Close.

func (*Stream) Context

func (d *Stream) Context() context.Context

Context returns the connection-scoped context - use this, not the original request context, in a long-running Recv/Send loop.

func (*Stream[In, Out]) Recv

func (s *Stream[In, Out]) Recv() (In, error)

Recv reads and JSON-decodes the next client->server frame. A peer close surfaces as an error - use websocket.CloseStatus(err) to distinguish a normal close from an abnormal one, same as using coder/websocket directly.

func (*Stream[In, Out]) Send

func (s *Stream[In, Out]) Send(msg Out) error

Send writes msg as the next server->client frame.

func (*Stream[In, Out]) SendError

func (s *Stream[In, Out]) SendError(err error) error

SendError writes err (normalized to an RRPCError - see toRRPCError) as the next server->client frame, distinguishable from a normal Send'd message by the client.

type UpgradeOptions

type UpgradeOptions struct {
	Subprotocols []string
}

UpgradeOptions configures a WebSocket upgrade. Leaving Subprotocols nil does NOT mean "no subprotocol negotiation" - if the client's handshake offered any (e.g. maf/rrpc-auth's "bearer, <token>" trick for carrying an auth token, since a browser's native WebSocket constructor can't set arbitrary headers on the handshake request), upgrade mirrors them back automatically. This isn't optional politeness: per RFC 6455 §4.1, a client that offered subprotocols MUST fail the connection if the server's response doesn't select one of them - every real implementation (browsers, the "ws" npm package, Go's x/net/websocket) enforces this, even though nothing in a raw HTTP Upgrade response makes the omission look wrong (curl, for instance, won't complain). Set Subprotocols explicitly only when a handler needs to require or choose among specific values itself.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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