ipc
import "github.com/tangoui/tango/ipc"本页由
site/tools/apigen从源码注释生成(按 darwin 构建标签选文件),请勿手改。
Package ipc implements Tango's IPC wire protocol (version 2) on top of raw page messages: calls (JS→Go request/response), events (both directions) and flow-controlled, bidirectional streams that either side may open and that carry JSON values and bytes both ways.
The package does not depend on the root tan package. A page connection is anything with a Send(msg string) method (*tango.Surface satisfies Conn). Feed every raw message from a page into Router.HandleMessage and call Router.Drop when the page goes away. Go code in the same process (a Go-drawn UI) reaches the same handlers with Router.Call and Router.Open, without the wire format.
In a bound Go method that takes a context.Context, use ConnFrom to get the connection for the calling window. For WebView calls, it is a *tango.Surface. Calls made in the same Go process with Router.Call have no window connection.
Wire format
One JSON object per raw message, tagged by the "tango" field. Messages without that field are not ipc and are left to the application.
Handshake. runtime-js sends hello when it starts (the page (re)loaded), with its own stream receive window in bytes in "win". Go drops everything of the previous document on that connection and replies with its stream receive window (SetStreamWindow, default DefaultWindowBytes). A hello without "proto":2 is answered with an error and logged with slog.Warn; that runtime's calls and streams then fail. Before Go's hello arrives, JS may already send calls, events and stream messages, counting on a window of DefaultWindowBytes.
{"tango":"hello","proto":2,"win":1048576}
{"tango":"hello","proto":2,"win":1048576}
{"tango":"hello","error":{"code":"bad_args","message":"runtime-js protocol mismatch"}}
The page's "win" is optional (older runtimes leave it out): a missing one, or one that is not an integer of at least MinWindowBytes, means DefaultWindowBytes; one above MaxPeerWindowBytes counts as that. The page may later change its window with win (runtime-js raises it once down:poll is ready); it applies to the streams opened after it and raises, never lowers, the window of open ones. Invalid ones, and one before hello, are ignored; a Go that predates it ignores it as an unknown message.
{"tango":"win","win":4194304}
Calls and events:
{"tango":"call","id":1,"method":"Greeter.Hello","args":["world"]}
{"tango":"ret","id":1,"result":"Hello world"}
{"tango":"ret","id":1,"error":{"message":"boom","code":"internal"}}
{"tango":"event","name":"progress","data":{"pct":42}}
Streams. Ids are allocated by the opener: JS uses odd numbers, Go even. Go never reuses an id on a connection across hello (until Router.Drop). Every stream message except open may travel in either direction:
{"tango":"stream","id":3,"op":"open","method":"Term.Attach","args":[]}
{"tango":"stream","id":3,"op":"accept","in":true}
{"tango":"stream","id":3,"op":"data","seq":0,"c":75,"data":{"cols":80}}
{"tango":"stream","id":3,"op":"data","seq":1,"c":69,"bin":"aGVsbG8="}
{"tango":"stream","id":3,"op":"ack","b":65536}
{"tango":"stream","id":3,"op":"boundary","seq":2}
{"tango":"stream","id":3,"op":"end","seq":2}
{"tango":"stream","id":3,"op":"close","seq":2}
{"tango":"stream","id":3,"op":"error","seq":2,"error":{"message":"...","code":"internal"}}
{"tango":"stream","id":3,"op":"cancel"}
The stream ops:
- accept: the receiving side of open confirms the stream before its handler runs. "in" tells whether that side receives data: false for a HandleStream handler (send only), which drops (and acknowledges) any data it gets; the opener's sends then fail with CodeBadArgs. The opener may send data before accept arrives. An unknown method is answered with error (CodeNotFound) instead of accept.
- data: one application message; frames are never split or merged. Exactly one of "data" (a JSON payload) and "bin" (a byte payload in standard, padded base64; "" is an empty byte frame) is present, otherwise the receiver fails the stream with CodeBadArgs. "seq" counts the frames of this direction from 0; the receiver delivers them in seq order. "c" is the charged size computed by the sender: the payload length (the sender's JSON encoding, or the raw bytes before base64) plus FrameOverhead. A missing c, or one below FrameOverhead, fails the stream with CodeBadArgs. A payload larger than MaxFrameBytes is never sent: the sending call fails with CodeBadArgs and the stream stays usable.
- boundary: reliable exclusive sequence bound, sent on the message channel once each lane frame is on its way (Go: when the lane accepted it; runtime-js: when the lane put it on the wire, not when it queued it, so a stalled page never starts the receiver's gap deadline early; every later message-channel frame of the stream, end and close included, then also waits for those lane frames). It neither ends the direction nor returns credit. A missing tail below it arms the same five-second gap deadline; contiguous receipt clears it. Only unresolved streams fail, even when there is no later frame/end and the send window is full. Go sends no boundary for a frame an ordered lane took (OrderedBinaryConn: the core's down:poll, one sequenced queue for messages and packets), since such a packet cannot be missing while later messages arrive.
- ack: returns "b" bytes of credit to the sender (the sum of the c of the frames read since the previous ack).
- end: half close. The sender of end sends no more data but still receives. Once both directions ended, the stream is complete.
- close: graceful full close. Like end, and the sender no longer receives: data still arriving is dropped, the peer's writes fail ("stream closed by peer"), and the peer sends nothing more on the stream. Go sends close when a stream handler returns nil.
- error: fails the stream in both directions. The receiver of error stops sending at once (its writes fail with the error) and sends nothing more; it still delivers the frames before "seq", then the error. Go sends it when a stream handler returns an error. An error without "seq" (a refused open, or another protocol-level failure) aborts at once.
- cancel: abandons the stream at once; unread data is dropped.
end, close and error carry in "seq" the number of data frames sent in that direction; the receiver acts on them only after every frame before them. A data payload larger than MaxFrameBytes fails the stream with CodeBadArgs. Unknown ops are ignored.
Flow control
Each direction of each stream has a window in bytes: the receive window the receiver advertised (Go's "win" in its hello reply; runtime-js's "win" in its hello or a later win message, DefaultWindowBytes when it gives none). The sender blocks while frames are in flight and the next frame's c would exceed the window; with nothing in flight a single frame may exceed it. The receiver returns a frame's c once the application has read the frame, and sends ack when the credit to return reaches a share of its window (Go: half; runtime-js: a quarter, so a page with a large window returns credit sooner), and also at once whenever a read leaves its receive queue empty. The share is the receiver's choice; a sender does not depend on it.
Fast lanes
A connection that implements BinaryConn may also carry stream byte frames on fast lanes: binary side channels, negotiated per direction, that skip JSON and base64. Only byte data frames ever use a lane; JSON frames, every control message (open, accept, ack, end, close, error, cancel) and the handshake stay on the message channel. Frames of one stream may be split between a lane and the message channel; the receiver reorders them by seq as usual, and end/close/error still wait for every frame before their seq. A frame that stays missing (later frames, or an end/close/error counting it, are here) for GapTimeout is taken as lost: the receiver fails the stream with an error carrying code "transport", sent to the other end as usual.
The opener of a stream keeps its byte frames off the lanes until the peer's accept arrived (they go on the message channel before that): a lane packet could overtake the open message and reach a peer that does not know the stream yet, which drops it. The acceptor may use a lane at once.
Windows with WebView2 SharedBuffer support enables down:shm and up:shm by default. Linux can opt in to down:poll and up:post where supported by WebKitGTK. See docs/specs/2026-11-13-ipc-duplex-streams.md §6.2 for platform defaults and settings.
When a lane is available, the hello reply carries the connection's BinaryConn.LaneHello JSON verbatim in "lanes"; without lanes the field is absent:
{"tango":"hello","proto":2,"win":1048576,"lanes":{"gen":1,"tok":"…","list":["down:poll","up:post"]}}
A lane carries packets, identical on every platform (big endian, not base64):
packet := count:u16 | frame*count
frame := streamID:u64 | seq:u64 | len:u32 | payload[len]
A packet may batch frames of several streams; count 0 is a valid empty packet. A frame on a lane has no "c": it is charged len+FrameOverhead. len is at most MaxFrameBytes, and a packet ends exactly after its last frame. Reusable document connections use SessionBinaryConn handles and Router.HandleBinarySession with the generation captured at authorization; simple non-reused BinaryConns may use Router.HandleBinary, which drops a malformed packet whole (logged with slog.Warn) and ignores frames for unknown streams.
常量
const (
CodeNotFound = "not_found"
CodeBadArgs = "bad_args"
CodeInternal = "internal"
CodeCanceled = "canceled"
// CodeTransport reports a broken transport: a stream fails with it
// when frames it is waiting for were lost (see GapTimeout).
CodeTransport = "transport"
)Error codes used on the wire.
const (
// ProtoVersion is the wire protocol version carried in "hello". A
// runtime-js speaking any other version is rejected.
ProtoVersion = 2
// DefaultWindowBytes is the default stream receive window in bytes.
DefaultWindowBytes = 1 << 20
// FrameOverhead is the fixed number of bytes charged per stream frame
// on top of its payload size.
FrameOverhead = 64
// MaxFrameBytes is the largest raw payload a single stream frame may
// carry.
MaxFrameBytes = 16 << 20
// MinWindowBytes is the smallest stream receive window either side may
// use (Router.SetStreamWindow; a smaller "win" from the page is
// ignored).
MinWindowBytes = 4096
// MaxPeerWindowBytes caps the receive window Go accepts from a page:
// a larger "win" is taken as this much, which bounds what Go queues
// toward the page per stream.
MaxPeerWindowBytes = 64 << 20
)Wire protocol v2 parameters (the JS runtime uses the same values).
const GapTimeout = 5 * time.SecondGapTimeout is how long a stream's receiver waits for a missing frame before failing the stream with CodeTransport. Frames of one stream may arrive on two transports (the message channel and a fast lane), so a later frame, or the end/close/error counting the missing one, can be here first; normally the gap closes within milliseconds.
函数
func AppendPacket
func AppendPacket(dst []byte, frames ...PacketFrame) []byteAppendPacket appends the packet carrying frames to dst and returns the extended slice. With no frames it appends the empty packet {0, 0}.
It panics if there are more than 65535 frames or a payload is larger than MaxFrameBytes: such a packet would never parse, so the caller has a bug.
类型
BinaryConn
type BinaryConn interface {
Conn
// LaneHello returns the JSON embedded in the "lanes" field of
// the hello reply; nil means this page has no fast lanes and the field
// is left out. The Router calls it once per hello from runtime-js,
// after dropping the previous document's state.
LaneHello() json.RawMessage
// SendBinary hands one packet to the downstream lane. It must not
// block; false means the lane is unavailable and the caller sends the
// frames as messages instead. On true the lane owns packet (the caller
// never touches it again); on false it must neither keep nor modify it.
// The Router calls it on a stream's writing goroutine with no ipc lock
// held other than that stream's send lock.
SendBinary(packet []byte) bool
// BinaryMinSize is the smallest byte payload, in bytes, worth sending
// on the downstream lane (smaller frames go as messages, for latency).
// A negative value means there is no downstream lane.
BinaryMinSize() int
}BinaryConn is a Conn with fast lanes: side channels that carry stream byte frames as binary packets (see the package comment) instead of JSON messages. *tango.Surface implements it. The Router finds it with a type assertion on the Conn. Feed a connection to one Router only: every hello a Router handles starts a new lane session, so two Routers on one surface would invalidate each other's lanes (unsupported).
Conn
type Conn interface {
Send(msg string)
}Conn is one page connection. Send delivers a raw message to the page; it must be safe from any goroutine and should not block. Conn values are used as map keys, so they must be comparable (typically a pointer).
func ConnFrom
func ConnFrom(ctx context.Context) (Conn, bool)ConnFrom returns the connection a call or stream handler is serving.
DuplexFunc
type DuplexFunc func(s *Stream, args json.RawMessage) errorDuplexFunc serves a bidirectional stream opened by JS: it reads with s.Receive* and writes with s.Write*, concurrently if it likes. args is the raw JSON argument array. Returning nil closes the stream; returning an error fails it. s.Context() is canceled when the stream ends or the connection drops.
Error
type Error struct {
Message string `json:"message"`
Code string `json:"code,omitempty"`
}Error is the error object carried on the wire. Handlers may return an *Error (directly or wrapped) to choose the code seen by JS; any other error is reported as CodeInternal (or CodeCanceled for context cancellation).
func NewError
func NewError(code, message string) *ErrorNewError returns an *Error with the given code and message.
func (*Error) Error
func (e *Error) Error() stringEventFunc
type EventFunc func(c Conn, data json.RawMessage)EventFunc receives an event sent by JS.
HandlerFunc
type HandlerFunc func(ctx context.Context, args json.RawMessage) (any, error)HandlerFunc serves a call. args is the raw JSON array of arguments ("[]" when none were sent). The returned value is JSON-encoded as the result. ctx is canceled when the connection is dropped.
Message
type Message struct {
Binary bool // true: Bytes holds the payload; false: JSON does
Bytes []byte // byte frame payload
JSON json.RawMessage // JSON frame payload
}Message is one frame received from the peer.
OrderedBinaryConn
type OrderedBinaryConn interface {
BinaryConn
// SendBinaryOrdered is SendBinary that also reports, for a packet it
// took, whether the lane that took it delivers it in order with every
// message sent after it on the connection and never loses it while
// those arrive. The Router then sends no boundary for the frame (the
// page cannot see later messages without the packet, so there is no
// gap to detect). ordered is meaningless when sent is false.
SendBinaryOrdered(packet []byte) (sent, ordered bool)
}OrderedBinaryConn is optionally implemented by a BinaryConn (or the transport a SessionBinaryConn returns) whose downstream lane may deliver packets in order with the message channel and as reliably as it (the core's down:poll: one sequenced queue for messages and packets). The Router uses SendBinaryOrdered instead of SendBinary when it is there.
PacketFrame
type PacketFrame struct {
Stream uint64
Seq uint64
Payload []byte // after ParsePacket: points into the input; copy it to keep it
}PacketFrame is one byte frame of a fast lane packet.
func ParsePacket
func ParsePacket(p []byte) ([]PacketFrame, error)ParsePacket decodes a fast lane packet. It fails unless p holds exactly the frames its count announces, each with a payload of at most MaxFrameBytes, and nothing after them. The returned payloads point into p (an empty payload is a non-nil empty slice).
Router
type Router struct {
// contains filtered or unexported fields
}Router dispatches ipc messages. The zero value is ready to use.
func NewRouter
func NewRouter() *RouterNewRouter returns an empty Router.
func (*Router) Call
func (r *Router) Call(ctx context.Context, method string, args ...any) (json.RawMessage, error)Call calls the handler registered with Handle for method, in process, and returns the JSON encoding of its result. args are JSON-encoded as the argument array, as a page's would be. Every error is an *Error with the code a page would see: CodeNotFound for an unknown method, the handler's *Error code, CodeInternal for other errors and panics, CodeCanceled when ctx is canceled.
The handler's context is canceled when ctx is; it carries no connection (ConnFrom reports ok=false) and none of ctx's values. If ctx is canceled Call returns at once, even if the handler is still running. Call blocks until then; do not call it on the UI thread.
func (*Router) Drop
func (r *Router) Drop(c Conn)Drop cancels every call and stream of c and forgets it. Call it when the page closes. Results of calls still running are discarded. A later message from c starts a fresh connection state.
func (*Router) Emit
func (r *Router) Emit(c Conn, name string, data any) errorEmit sends an event to the page behind c.
func (*Router) Handle
func (r *Router) Handle(name string, fn HandlerFunc)Handle registers fn for calls to name, replacing any previous handler.
func (*Router) HandleBinary
func (r *Router) HandleBinary(c Conn, packet []byte)HandleBinary processes one upstream fast lane packet from c (see the package comment). Each frame goes to the stream with its id on c, charged len(payload)+FrameOverhead; frames for unknown or finished streams are ignored. A malformed packet is dropped whole and logged with slog.Warn. HandleBinary does not keep packet: payloads are copied. It never blocks.
HandleBinary is only for simple connections that never host a second document (no SessionBinaryConn). A SessionBinaryConn such as *tango.Surface needs HandleBinarySession with the generation its packet was authorized for: HandleBinary drops such packets and logs one slog.Warn per Router naming HandleBinarySession.
func (*Router) HandleBinarySession
func (r *Router) HandleBinarySession(c Conn, generation uint64, packet []byte)HandleBinarySession delivers only into the authorized document session. Use with App.OnBinary; generation is captured at ingress authorization.
func (*Router) HandleDuplex
func (r *Router) HandleDuplex(name string, fn DuplexFunc)HandleDuplex registers fn for bidirectional streams JS opens with name, replacing any previous stream handler (StreamFunc or DuplexFunc) for name. Go accepts the stream with in:true.
func (*Router) HandleMessage
func (r *Router) HandleMessage(c Conn, msg string) boolHandleMessage processes one raw message from c. It reports whether the message belonged to ipc (a JSON object with a "tango" field); other messages are left to the caller. It never blocks: calls and streams run on their own goroutines.
func (*Router) HandleStream
func (r *Router) HandleStream(name string, fn StreamFunc)HandleStream registers fn for streams JS opens with name, replacing any previous stream handler (StreamFunc or DuplexFunc) for name. The stream only sends: Go accepts it with in:false, and data JS sends anyway is dropped (its credit is still returned).
func (*Router) Has
func (r *Router) Has(name string) boolHas reports whether a call or stream handler is registered for name.
func (*Router) On
func (r *Router) On(name string, fn EventFunc) (off func())On subscribes fn to events named name sent by JS. Handlers run synchronously inside HandleMessage (usually the main thread), so they must not block. The returned function unsubscribes.
func (*Router) OnPanic
func (r *Router) OnPanic(fn func(c Conn, where string, value any, stack []byte))OnPanic sets fn to be told about a panic recovered in a call or stream handler, on the handler's goroutine. where is "binding Name" or "stream Name". The panic still becomes a CodeInternal error for the caller; reporting cannot change that, and nothing exits the process.
Without fn, a panic on a connection that is a *tango.Surface goes to that app's panic handling (tango.Options.OnPanic or its default, report only: a keepRunning false is ignored for bindings); on other connections it is logged with log/slog.
func (*Router) Open
func (r *Router) Open(ctx context.Context, method string, args ...any) (*Stream, error)Open opens a stream to the handler registered with HandleStream or HandleDuplex for method, in process, and returns the client end. args are JSON-encoded as the argument array, as a page's would be. The client end has the same methods and semantics as the serving end (Write, WriteBytes, Receive*, CloseSend, Close, CloseWithError, Context); for a HandleStream handler, Write* returns an *Error with CodeBadArgs ("stream does not accept data"). Both directions use SetStreamWindow's window.
Open returns once the stream is accepted, which in process is at once. An unknown method returns an *Error with CodeNotFound. Canceling ctx cancels the stream (both ends see CodeCanceled), whether before or after Open returns; a ctx already done when Open is called returns its cause as an *Error and starts nothing.
The handler cannot tell an in-process client from a page, except that ConnFrom reports ok=false: in-process streams belong to no connection, so Drop and page reloads do not affect them. A panic in the handler is reported through OnPanic with a nil Conn (or logged) and fails the stream with CodeInternal.
Open, Receive* and Write* may block; do not call them on the UI thread.
The caller must end the stream: Close it (or read to the end and let the handler close it) or cancel ctx. An abandoned stream is never collected: its handler goroutine keeps running, blocked on the stream.
func (*Router) OpenStream
func (r *Router) OpenStream(c Conn, method string, args ...any) (*Stream, error)OpenStream starts a Go→JS stream: JS receives it through tango.onStream(method, fn). args are JSON-encoded as the argument array. Write the values, then Close (or CloseWithError).
func (*Router) SetStreamWindow
func (r *Router) SetStreamWindow(n int)SetStreamWindow sets Go's stream receive window in bytes, advertised to runtime-js in the hello reply. The default is DefaultWindowBytes. It panics if n < 4096.
Call it before pages load (and before in-process streams open), typically right after NewRouter. A page uses the window from its hello reply for all its streams, so lowering the window after a page's hello lets that page send more than Go now accepts, which fails its streams with "flow control violated".
SessionBinaryConn
type SessionBinaryConn interface {
BinarySession() (generation uint64, transport BinaryConn)
// DropBinarySession retires the transport identity, even before LaneHello.
// Called under Router.mu: must not invoke callbacks or reenter Router.
DropBinarySession()
}SessionBinaryConn binds sends to an immutable document generation. Reusable surfaces must implement it; simple in-process BinaryConns may omit it. BinarySession is captured once when connState is published, never per send. Upstream packets for it go through Router.HandleBinarySession (HandleBinary drops them). One Router per surface: two Routers on one surface are unsupported.
Stream
type Stream struct {
// contains filtered or unexported fields
}Stream is one end of a stream: the writer handed to a StreamFunc or DuplexFunc, the value Router.OpenStream returns for Go-opened streams, or the client end Router.Open returns for in-process streams.
A Stream talks to the other end only through its peer (frames and control messages out; onCtl in), its parent context and its release function, so the same state machine serves runtime-js connections and in-process clients.
Locking: writeMu serializes frame hand-off and the local end/close/error, so those control messages follow every frame they count. A local close never waits for credit while holding it: it first marks the send direction terminal under mu, which makes a writer blocked on credit return at once. readMu serializes Receive* calls. mu guards the state below it and is never held while calling the peer. onCtl and onFrame take only mu and never block: a peer may deliver synchronously while this side holds writeMu or readMu.
Lifecycle: each direction ends on its own. The send direction is terminal after a local CloseSend/Close/CloseWithError or a peer close/cancel/error; the receive direction after Receive* returned io.EOF (or the peer's error), a local Close, or a peer cancel. When both are terminal the stream has fully finished: release is called (once) and the context is canceled. Aborts (peer cancel, peer error without seq, local error, Drop) finish at once; a peer error with seq is ordered like end/close (see peerError).
func (*Stream) Close
func (s *Stream) Close() errorClose ends the stream normally: it sends close with the number of frames sent, which also tells the peer this side no longer receives. Unread and later frames are dropped without returning their credit, Receive* returns io.EOF and Write* an *Error with CodeCanceled. A Write blocked on credit in another goroutine fails at once and sends nothing. Nothing is sent if the stream already finished or the peer closed it. Further calls are no-ops.
func (*Stream) CloseSend
func (s *Stream) CloseSend() errorCloseSend ends this side's send direction: it sends end with the number of frames sent, and Write* returns an *Error with CodeCanceled ("stream closed") from then on. The stream keeps receiving until the peer ends its direction. A Write blocked on credit in another goroutine fails at once and sends nothing. It is a no-op once the send direction has ended.
func (*Stream) CloseWithError
func (s *Stream) CloseWithError(err error) errorCloseWithError fails the stream in both directions: it sends error with the number of frames sent, and the peer sees err (an *Error keeps its code, others become "internal") after the frames sent before it. This side does not see err: its own Receive* and Write* return an *Error with CodeCanceled ("stream closed") from then on. Like Close, it does not wait for credit, and it is a no-op once Close or CloseWithError was called.
func (*Stream) Context
func (s *Stream) Context() context.ContextContext is canceled when the stream has fully finished (both directions terminal) or was aborted: canceled or failed by either side, or the connection dropped. A half-closed stream (CloseSend, or the peer's end) keeps it live; so does a peer error while frames sent before it are still unread (Receive* delivers them, then the error, then it is canceled).
func (*Stream) ID
func (s *Stream) ID() uint64ID returns the stream id on the wire.
func (*Stream) ReadWriter
func (s *Stream) ReadWriter() io.ReadWriteCloserReadWriter returns s as an io.ReadWriteCloser over byte frames:
- Read reads the byte frames as one continuous byte stream: frame boundaries are invisible, and the unread rest of a frame is kept for the next Read. Empty byte frames contribute nothing. It returns io.EOF once the peer ended its direction and everything before the end was read. A JSON frame at the head of the queue makes Read return an *Error with CodeBadArgs and stays queued (Receive can take it). Other errors are those of ReceiveBytes.
- Write sends p as one byte frame, or, when p is larger than MaxFrameBytes, as consecutive frames of at most MaxFrameBytes each (the view keeps no boundaries, so a write may be split); an empty p returns 0, nil and sends nothing (as net.Conn does). Frames of one Write are not interleaved with another Write's through the view. On error it returns the bytes of the frames already sent.
- Close is CloseSend: a half close, so the peer sees the end (say after io.Copy into the view) while this side keeps reading.
Every call returns the same view, with a single read leftover. One reader and one writer may use it concurrently; concurrent Reads (or Writes) are serialized. Receive* called directly on s does not see the read leftover: it takes the next whole frame after it.
func (*Stream) Receive
func (s *Stream) Receive() (Message, error)Receive returns the next frame from the peer, blocking until one arrives. It returns io.EOF once the peer ended its direction (end or close) and every frame before the end was read, or once this side called Close (no longer receiving; unread frames are dropped). When the peer failed the stream (its CloseWithError, or a page handler's error), the frames it sent before failing are delivered first and then the peer's *Error is returned. It returns context.Cause of the stream context once the stream is canceled or aborted, or the connection dropped.
func (*Stream) ReceiveBytes
func (s *Stream) ReceiveBytes() ([]byte, error)ReceiveBytes is Receive for a byte frame. If the next frame is a JSON frame it returns an *Error with CodeBadArgs and leaves the frame queued.
func (*Stream) ReceiveJSON
func (s *Stream) ReceiveJSON(v any) errorReceiveJSON receives a JSON frame and decodes it into v. If the next frame is a byte frame it returns an *Error with CodeBadArgs and leaves the frame queued; if decoding fails it returns an *Error with CodeBadArgs and the frame is consumed.
func (*Stream) Write
func (s *Stream) Write(v any) errorWrite JSON-encodes v and sends it as one JSON frame. It blocks while the frame does not fit in the peer's byte window (FrameOverhead plus the encoded size is charged per frame; a frame is always sent when nothing is in flight). An encoding larger than MaxFrameBytes fails with CodeBadArgs and leaves the stream usable.
func (*Stream) WriteBytes
func (s *Stream) WriteBytes(p []byte) errorWriteBytes sends p as one byte frame, with the same flow control as Write (charged len(p)+FrameOverhead). p may be reused once WriteBytes returns. A p larger than MaxFrameBytes fails with CodeBadArgs and leaves the stream usable.
StreamFunc
type StreamFunc func(ctx context.Context, args json.RawMessage, w StreamWriter) errorStreamFunc serves a stream opened by JS. Values written to w are delivered in order. Returning nil ends the stream; returning an error fails it. ctx is canceled when JS cancels or closes the stream or the connection is dropped.
StreamWriter
type StreamWriter interface {
// Write JSON-encodes v and sends it. It blocks while the consumer's
// byte window is full (see Stream.Write), and returns context.Cause of
// the stream context once the stream is canceled or the connection
// dropped.
Write(v any) error
// Context is canceled when the consumer cancels or the connection drops.
Context() context.Context
}StreamWriter is the producer side of a stream.