
ExamplesExample
Streaming an agent’s progress to a browser
An agent’s progress streamed to a web page with net/http and server-sent events.
On the agent compass The whole loop, all four stagesServer-sent events (SSE) keep one HTTP response open and send messages down it as they happen.
Reading them from the model’s API turns them into the agent’s own events: text as it arrives, each tool call, each result, the end of a turn (one model call and its tools), and the end of a run.
New to streams in Go? Start with Streams in Go, which covers flushing and the event stream format.
This example sends those events onward, from a Go server to a web page, so a person can watch a run as it happens and stop it.
It is the companion code’s ssebrowser example, built on net/http alone, with tests that run under the race detector.
The model is scripted, a replay of a run on the duration project, the small Go package whose failing test the book’s first agent fixes, slowed down so you can watch it, so everything runs offline.
The tools, go test among them, run for real.
Run it
From the code directory of a clone of the companion repository:
$ go run ./ssebrowser
Open the address it prints and press Run.
The page shows the model’s text as it streams, each tool call and its result, and the end of each turn.
Press Stop partway through and the run on the server stops too.
Press Ctrl-C in the terminal to stop the server.
To see the raw stream without a browser, run this in a second terminal while the server is up (-N turns off curl’s output buffering, so each event prints as it arrives):
$ curl -N 'http://localhost:8080/events?task=fix'
: run started
event: text
data: {"text":"I'll "}
event: text
data: {"text":"run "}
The lines continue until the run ends. Each event is a line naming its kind and a line of JSON, followed by a blank line; the first line, starting with a colon, is a comment that the browser ignores.
The page sends its task in the query string, but the scripted model gives the same replies whatever the task says.
One request, one stream
The event stream is a long-lived GET, since a browser’s EventSource can’t send anything else.
Here is the handler:
// events streams one run's events to the client. The task comes in the
// query string, since a browser's EventSource can only send a GET.
func (s *Server) events(w http.ResponseWriter, r *http.Request) {
task := r.URL.Query().Get("task")
if task == "" {
http.Error(w, "missing task", http.StatusBadRequest)
return
}
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("X-Accel-Buffering", "no")
st := &stream{w: w, rc: http.NewResponseController(w),
wait: s.WriteWait}
ctx, cancel := context.WithCancel(r.Context())
events := s.start(ctx, task)
defer func() {
cancel()
for range events {
}
}()
if err := s.pump(st, events); err != nil {
slog.DebugContext(ctx, "event stream ended", "err", err)
}
}
Three headers make it a stream: text/event-stream tells the browser what it is reading, Cache-Control: no-cache keeps caches out of the way, and X-Accel-Buffering: no asks a proxy such as nginx not to hold events back in a buffer.
The run gets a context derived from the request’s. When the browser closes the connection, because the person pressed Stop or closed the tab, the request’s context ends, and the run’s model call and tools stop with it. The deferred function cancels the run and then reads the channel until it closes, so the goroutine that drives the agent is sure to have finished before the handler returns. That goroutine has one owner, the handler, and one way to stop, the context.
The agent runs in its own goroutine for a reason: while the model is thinking, nothing arrives for a while, and the handler has to keep sending something.
pump, in the same file, waits on two things at once, the next event and a ticker, and sends a comment line, : heartbeat, when the ticker fires first.
Proxies and load balancers may close a connection that stays silent too long; the heartbeat keeps it open, and EventSource ignores comment lines.
Only the handler writes to the client, because a ResponseWriter isn’t safe to use from two goroutines.
Every write is flushed, with a deadline
// stream writes an event stream to one client.
type stream struct {
w io.Writer
rc *http.ResponseController
wait time.Duration
}
// send writes msg and flushes it to the client at once. A client that
// doesn't take it within s.wait is dropped: the write fails, and the
// handler stops.
func (s *stream) send(msg string) error {
err := s.rc.SetWriteDeadline(time.Now().Add(s.wait))
if err != nil {
return fmt.Errorf("set write deadline: %w", err)
}
if _, err := io.WriteString(s.w, msg); err != nil {
return fmt.Errorf("write event: %w", err)
}
if err := s.rc.Flush(); err != nil {
return fmt.Errorf("flush event: %w", err)
}
return nil
}
http.ResponseController gives a handler two things a plain ResponseWriter hides.
Flush pushes each event to the client at once instead of letting it wait in a buffer, which is the whole point of a stream.
SetWriteDeadline sets a limit on each write: a client that stops reading, with the connection still open, would otherwise hold its goroutine and its run forever.
Past the deadline the write fails, pump returns, and the deferred cancel stops the run.
The program allows ten seconds per write and sends a heartbeat every fifteen.
The wire format
Each event is a line naming its kind, a line of JSON, and a blank line:
// encode formats ev as one event in the stream: a line naming its kind,
// a line of JSON data, and a blank line that ends the event. JSON
// escapes newlines, so the data always fits on its one line.
func encode(ev agent.Event) (string, error) {
name, d, err := wire(ev)
if err != nil {
return "", err
}
b, err := json.Marshal(d, jsontext.AllowInvalidUTF8(true))
if err != nil {
return "", fmt.Errorf("encode %s event: %w", name, err)
}
return fmt.Sprintf("event: %s\ndata: %s\n\n", name, b), nil
}
A newline inside the data would break its single data: line, and a blank line would end the event; JSON escapes newlines, so a tool result of any length fits on its single data: line.
Naming each event lets the page attach one listener per kind instead of parsing a type field out of every message.
The page
The page reads the stream with EventSource, the browser’s built-in client for server-sent events:
run.onclick = () => {
log.replaceChildren();
text = null;
const task = document.getElementById("task").value;
es = new EventSource("/events?task=" + encodeURIComponent(task));
run.disabled = true;
stop.disabled = false;
const on = (kind, f) =>
es.addEventListener(kind, e => f(JSON.parse(e.data)));
on("text", d => {
text ??= line("text", "");
text.textContent += d.text;
});
on("call", d => {
text = null;
line("call", "→ " + d.name + " " + d.args);
});
on("result", d =>
line(d.is_error ? "result error" : "result", d.content));
on("turn", d => {
text = null;
line("turn meta", "end of turn " + d.turn);
});
on("stopped", d => d.error
? done("stopped: " + d.error, "meta error")
: done("answered", "meta"));
es.onerror = () => done("connection lost", "meta error");
};
One detail matters more than it looks.
When the stream ends, EventSource reconnects by default, and here a reconnection would start a whole new run.
So the page closes the EventSource itself when it sees the stopped event or an error, and the Stop button does the same.
Shutting down
When you press Ctrl-C, the program cancels every open stream and its run, then shuts the server down.
A stream never goes idle by itself, so http.Server.Shutdown, which waits for active connections to go idle, would wait out its whole timeout.
The program gives the server a BaseContext that returns the program’s own context, which Ctrl-C cancels (this listing is the first half of the serve function; the rest starts the server and calls Shutdown):
// serve runs the server until ctx is done, then shuts it down.
func serve(ctx context.Context, addr string, w io.Writer) error {
s := &Server{
Run: demo(700*time.Millisecond, 40*time.Millisecond),
Heartbeat: 15 * time.Second,
WriteWait: 10 * time.Second,
}
srv := &http.Server{
Handler: s.Handler(),
ReadHeaderTimeout: 5 * time.Second,
BaseContext: func(net.Listener) context.Context {
return ctx
},
}
ln, err := new(net.ListenConfig).Listen(ctx, "tcp", addr)
if err != nil {
return fmt.Errorf("listen: %w", err)
}
_, err = fmt.Fprintf(w, "open http://%s\n", ln.Addr())
if err != nil {
return fmt.Errorf("print address: %w", err)
}
Every request’s context descends from it, so cancelling it ends every open stream and its run, and Shutdown then finds nothing left to wait for.
ReadHeaderTimeout bounds how long a client may take to send its headers, a limit worth setting on any server that faces the internet.
What the tests check
$ go test -race ./ssebrowser
The tests read the stream from an httptest server and check the headers and every event of a full run, that a quiet stream sends heartbeats, that a client leaving cancels the run, that a failed write stops the handler, that bad requests are refused, and that shutdown ends open streams.
What a real service adds
The example is small on purpose, and its README lists what a public service would change; an agent as a service builds one:
- Error text. The page shows a run’s error as it is; a public service would send a short stop reason instead of internal detail.
- Limits. Each request starts a run. A real service caps how many run at once, and per user, since each one spends money.
- Reconnecting. A dropped connection loses the run. To let a client pick up where it left off, give each event an
id:line, keep the run going apart from the request, and resume from theLast-Event-IDheader the browser sends when it reconnects.
Key files
ssebrowser/server.go: the handler, the goroutine that runs the agent, and the writes.ssebrowser/sse.go: each agent event in the event stream format.ssebrowser/index.html: the page.ssebrowser/main.go: the program, the scripted run, and the server’s start and shutdown.
type Server struct {
Run Runner
Heartbeat time.Duration // how often a quiet stream sends a comment
WriteWait time.Duration // how long a client may take to read one
}
Server serves a page that runs the agent, and the stream of events the page reads while the run goes on.
Server serves a page that runs the agent, and the stream of events the page reads while the run goes on. type Server struct { Run Runner Heartbeat time.Duration // how often a quiet stream sends a comment WriteWait time.Duration // how long a client may take to read one }. In ssebrowser/server.go, line 28.
func (s *Server) events(w http.ResponseWriter, r *http.Request)
events streams one run's events to the client.
events streams one run's events to the client. func (s *Server) events(w http.ResponseWriter, r *http.Request). In ssebrowser/server.go, line 53.
var w http.ResponseWriter
var w http.ResponseWriter. In ssebrowser/server.go, line 53.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type ResponseWriter interface {
// Header returns the header map that will be sent by
// [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which
// [Handler] implementations can set HTTP trailers.
//
// Changing the header map after a call to [ResponseWriter.WriteHeader] (or
// [ResponseWriter.Write]) has no effect unless the HTTP status code was of the
// 1xx class or the modified headers are trailers.
//
// There are two ways to set Trailers. The preferred way is to
// ...
}
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response.
A ResponseWriter interface is used by an HTTP handler to construct an HTTP response. type ResponseWriter interface { // Header returns the header map that will be sent by // [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which // [Handler] implementations can set HTTP trailers. // // Changing the header map after a call to [ResponseWriter.WriteHeader] (or // [ResponseWriter.Write]) has no effect unless the HTTP status code was of the // 1xx class or the modified headers are trailers. // // There are two ways to set Trailers. The preferred way is to // ... }. Documented at pkg.go.dev, net/http.ResponseWriter.
type Request struct {
// Method specifies the HTTP method (GET, POST, PUT, etc.).
// For client requests, an empty string means GET.
Method string
// URL specifies either the URI being requested (for server
// requests) or the URL to access (for client requests).
//
// For server requests, the URL is parsed from the URI
// supplied on the Request-Line as stored in RequestURI. For
// ...
}
A Request represents an HTTP request received by a server or to be sent by a client.
A Request represents an HTTP request received by a server or to be sent by a client. type Request struct { // Method specifies the HTTP method (GET, POST, PUT, etc.). // For client requests, an empty string means GET. Method string // URL specifies either the URI being requested (for server // requests) or the URL to access (for client requests). // // For server requests, the URL is parsed from the URI // supplied on the Request-Line as stored in RequestURI. For // ... }. Documented at pkg.go.dev, net/http.Request.
field URL *url.URL
URL specifies either the URI being requested (for server requests) or the URL to access (for client requests).
URL specifies either the URI being requested (for server requests) or the URL to access (for client requests). field URL *url.URL. Documented at pkg.go.dev, net/http.Request.URL.
func (u *URL) Query() Values
Query parses RawQuery and returns the corresponding values.
Query parses RawQuery and returns the corresponding values. func (u *URL) Query() Values. Documented at pkg.go.dev, net/url.URL.Query.
func (v Values) Get(key string) string
Get gets the first value associated with the given key.
Get gets the first value associated with the given key. func (v Values) Get(key string) string. Documented at pkg.go.dev, net/url.Values.Get.
func Error(w ResponseWriter, error string, code int)
Error replies to the request with the specified error message and HTTP code.
Error replies to the request with the specified error message and HTTP code. func Error(w ResponseWriter, error string, code int). Documented at pkg.go.dev, net/http.Error.
const StatusBadRequest = 400
RFC 9110, 15.5.1
RFC 9110, 15.5.1 const StatusBadRequest = 400. Documented at pkg.go.dev, net/http.StatusBadRequest.
func (ResponseWriter) Header() Header
Header returns the header map that will be sent by [ResponseWriter.WriteHeader].
net/http.ResponseWriter.Header
Header returns the header map that will be sent by [ResponseWriter.WriteHeader]. func (ResponseWriter) Header() Header. Documented at pkg.go.dev, net/http.ResponseWriter.Header.
func (h Header) Set(key, value string)
Set sets the header entries associated with key to the single element value.
Set sets the header entries associated with key to the single element value. func (h Header) Set(key, value string). Documented at pkg.go.dev, net/http.Header.Set.
type stream struct {
w io.Writer
rc *http.ResponseController
wait time.Duration
}
stream writes an event stream to one client.
stream writes an event stream to one client. type stream struct { w io.Writer rc *http.ResponseController wait time.Duration }. In ssebrowser/server.go, line 142.
field rc *http.ResponseController
field rc *http.ResponseController. In ssebrowser/server.go, line 144.
func NewResponseController(rw ResponseWriter) *ResponseController
NewResponseController creates a [ResponseController] for a request.
net/http.NewResponseController
NewResponseController creates a [ResponseController] for a request. func NewResponseController(rw ResponseWriter) *ResponseController. Documented at pkg.go.dev, net/http.NewResponseController.
field wait time.Duration
field wait time.Duration. In ssebrowser/server.go, line 145.
field WriteWait time.Duration
how long a client may take to read one
how long a client may take to read one field WriteWait time.Duration. In ssebrowser/server.go, line 31.
var ctx context.Context
var ctx context.Context. In ssebrowser/server.go, line 65.
var cancel context.CancelFunc
var cancel context.CancelFunc. In ssebrowser/server.go, line 65.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
WithCancel returns a derived context that points to the parent context but has a new Done channel.
WithCancel returns a derived context that points to the parent context but has a new Done channel. func WithCancel(parent Context) (ctx Context, cancel CancelFunc). Documented at pkg.go.dev, context.WithCancel.
func (r *Request) Context() context.Context
Context returns the request's context.
Context returns the request's context. func (r *Request) Context() context.Context. Documented at pkg.go.dev, net/http.Request.Context.
var events <-chan agent.Event
var events <-chan agent.Event. In ssebrowser/server.go, line 66.
func (s *Server) start(ctx context.Context,
task string) <-chan agent.Event
start runs the agent in a goroutine and sends its events on the channel it returns.
start runs the agent in a goroutine and sends its events on the channel it returns. func (s *Server) start(ctx context.Context, task string) <-chan agent.Event. In ssebrowser/server.go, line 121.
func (s *Server) pump(st *stream, events <-chan agent.Event) error
pump sends events to the client as they arrive, and a heartbeat when none has arrived for a while, until the run stops or a send fails.
pump sends events to the client as they arrive, and a heartbeat when none has arrived for a while, until the run stops or a send fails. func (s *Server) pump(st *stream, events <-chan agent.Event) error. In ssebrowser/server.go, line 83.
var nil Type
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type.
nil is a predeclared identifier representing the zero value for a pointer, channel, func, interface, map, or slice type. var nil Type. Documented at pkg.go.dev, builtin.nil.
package slog ("log/slog")
Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs.
Package slog provides structured logging, in which log records include a message, a severity level, and various other attributes expressed as key-value pairs. package slog ("log/slog"). Documented at pkg.go.dev, log/slog.
func DebugContext(ctx context.Context, msg string, args ...any)
DebugContext calls [Logger.DebugContext] on the default logger.
DebugContext calls [Logger.DebugContext] on the default logger. func DebugContext(ctx context.Context, msg string, args ...any). Documented at pkg.go.dev, log/slog.DebugContext.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
type Writer interface {
Write(p []byte) (n int, err error)
}
Writer is the interface that wraps the basic Write method.
Writer is the interface that wraps the basic Write method. type Writer interface { Write(p []byte) (n int, err error) }. Documented at pkg.go.dev, io.Writer.
type ResponseController struct {
rw ResponseWriter
}
A ResponseController is used by an HTTP handler to control the response.
A ResponseController is used by an HTTP handler to control the response. type ResponseController struct { rw ResponseWriter }. Documented at pkg.go.dev, net/http.ResponseController.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
type Duration int64
A Duration represents the elapsed time between two instants as an int64 nanosecond count.
A Duration represents the elapsed time between two instants as an int64 nanosecond count. type Duration int64. Documented at pkg.go.dev, time.Duration.
func (s *stream) send(msg string) error
send writes msg and flushes it to the client at once.
send writes msg and flushes it to the client at once. func (s *stream) send(msg string) error. In ssebrowser/server.go, line 151.
type string string
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text.
string is the set of all strings of 8-bit bytes, conventionally but not necessarily representing UTF-8-encoded text. type string string. Documented at pkg.go.dev, builtin.string.
type error interface {
Error() string
}
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error. type error interface { Error() string }. Documented at pkg.go.dev, builtin.error.
func (c *ResponseController) SetWriteDeadline(deadline time.Time) error
SetWriteDeadline sets the deadline for writing the response.
net/http.ResponseController.SetWriteDeadline
SetWriteDeadline sets the deadline for writing the response. func (c *ResponseController) SetWriteDeadline(deadline time.Time) error. Documented at pkg.go.dev, net/http.ResponseController.SetWriteDeadline.
func Now() Time
Now returns the current local time.
Now returns the current local time. func Now() Time. Documented at pkg.go.dev, time.Now.
func (t Time) Add(d Duration) Time
Add returns the time t+d.
Add returns the time t+d. func (t Time) Add(d Duration) Time. Documented at pkg.go.dev, time.Time.Add.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Errorf(format string, a ...any) (err error)
Errorf formats according to a format specifier and returns the string as a value that satisfies error.
Errorf formats according to a format specifier and returns the string as a value that satisfies error. func Errorf(format string, a ...any) (err error). Documented at pkg.go.dev, fmt.Errorf.
func WriteString(w Writer, s string) (n int, err error)
WriteString writes the contents of the string s to w, which accepts a slice of bytes.
WriteString writes the contents of the string s to w, which accepts a slice of bytes. func WriteString(w Writer, s string) (n int, err error). Documented at pkg.go.dev, io.WriteString.
func (c *ResponseController) Flush() error
Flush flushes buffered data to the client.
net/http.ResponseController.Flush
Flush flushes buffered data to the client. func (c *ResponseController) Flush() error. Documented at pkg.go.dev, net/http.ResponseController.Flush.
func encode(ev agent.Event) (string, error)
encode formats ev as one event in the stream: a line naming its kind, a line of JSON data, and a blank line that ends the event.
encode formats ev as one event in the stream: a line naming its kind, a line of JSON data, and a blank line that ends the event. func encode(ev agent.Event) (string, error). In ssebrowser/sse.go, line 34.
package agent ("github.com/blackwell-systems/go-agents-book/code/ch06/agent")
Package agent is the agent loop and the types it works with.
Package agent is the agent loop and the types it works with. package agent ("github.com/blackwell-systems/go-agents-book/code/ch06/agent"). In ch06/agent.
type Event struct {
Kind EventKind
Text string // TextEvent: the new text
Call ToolCall // CallEvent: the call
Tool Message // ToolResultEvent: the tool message
Turn int // TurnEvent: how many turns have ended
Result Result // StoppedEvent: the run, as far as it went
Err error // StoppedEvent: why it stopped; nil for an answer
}
An Event is something that happened during a run.
An Event is something that happened during a run. type Event struct { Kind EventKind Text string // TextEvent: the new text Call ToolCall // CallEvent: the call Tool Message // ToolResultEvent: the tool message Turn int // TurnEvent: how many turns have ended Result Result // StoppedEvent: the run, as far as it went Err error // StoppedEvent: why it stopped; nil for an answer }. In ch06/agent/events.go, line 26.
func wire(ev agent.Event) (string, data, error)
wire names an event's kind for the page and picks out its data.
wire names an event's kind for the page and picks out its data. func wire(ev agent.Event) (string, data, error). In ssebrowser/sse.go, line 51.
package json ("encoding/json/v2")
Package json implements semantic processing of JSON as specified in RFC 8259.
Package json implements semantic processing of JSON as specified in RFC 8259. package json ("encoding/json/v2"). Documented at pkg.go.dev, encoding/json/v2.
func Marshal(in any, opts ...Options) (out []byte, err error)
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options).
Marshal serializes a Go value as a []byte according to the provided marshal and encode options (while ignoring unmarshal or decode options). func Marshal(in any, opts ...Options) (out []byte, err error). Documented at pkg.go.dev, encoding/json/v2.Marshal.
package jsontext ("encoding/json/jsontext")
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785.
Package jsontext implements syntactic processing of JSON as specified in RFC 4627, RFC 7159, RFC 7493, RFC 8259, and RFC 8785. package jsontext ("encoding/json/jsontext"). Documented at pkg.go.dev, encoding/json/jsontext.
func AllowInvalidUTF8(v bool) Options
AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, which will be mangled as the Unicode replacement character, U+FFFD.
encoding/json/jsontext.AllowInvalidUTF8
AllowInvalidUTF8 specifies that JSON strings may contain invalid UTF-8, which will be mangled as the Unicode replacement character, U+FFFD. func AllowInvalidUTF8(v bool) Options. Documented at pkg.go.dev, encoding/json/jsontext.AllowInvalidUTF8.
const true = 0 == 0
Untyped bool.
Untyped bool. const true = 0 == 0. Documented at pkg.go.dev, builtin.true.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Sprintf(format string, a ...any) string
Sprintf formats according to a format specifier and returns the resulting string.
Sprintf formats according to a format specifier and returns the resulting string. func Sprintf(format string, a ...any) string. Documented at pkg.go.dev, fmt.Sprintf.
func serve(ctx context.Context, addr string, w io.Writer) error
serve runs the server until ctx is done, then shuts it down.
serve runs the server until ctx is done, then shuts it down. func serve(ctx context.Context, addr string, w io.Writer) error. In ssebrowser/main.go, line 46.
var ctx context.Context
var ctx context.Context. In ssebrowser/main.go, line 46.
package context ("context")
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.
Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. package context ("context"). Documented at pkg.go.dev, context.
type Context interface {
// Deadline returns the time when work done on behalf of this context
// should be canceled. Deadline returns ok==false when no deadline is
// set. Successive calls to Deadline return the same results.
Deadline() (deadline time.Time, ok bool)
// Done returns a channel that's closed when work done on behalf of this
// context should be canceled. Done may return nil if this context can
// never be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// ...
}
A Context carries a deadline, a cancellation signal, and other values across API boundaries.
A Context carries a deadline, a cancellation signal, and other values across API boundaries. type Context interface { // Deadline returns the time when work done on behalf of this context // should be canceled. Deadline returns ok==false when no deadline is // set. Successive calls to Deadline return the same results. Deadline() (deadline time.Time, ok bool) // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Done may return nil if this context can // never be canceled. Successive calls to Done return the same value. // The close of the Done channel may happen asynchronously, // ... }. Documented at pkg.go.dev, context.Context.
package io ("io")
Package io provides basic interfaces to I/O primitives.
Package io provides basic interfaces to I/O primitives. package io ("io"). Documented at pkg.go.dev, io.
func demo(think, word time.Duration) Runner
demo returns a Runner for chapter 6's agent on a fresh copy of the duration project, with a scripted model paced so a person can watch.
demo returns a Runner for chapter 6's agent on a fresh copy of the duration project, with a scripted model paced so a person can watch. func demo(think, word time.Duration) Runner. In ssebrowser/main.go, line 92.
package time ("time")
Package time provides functionality for measuring and displaying time.
Package time provides functionality for measuring and displaying time. package time ("time"). Documented at pkg.go.dev, time.
const Millisecond = 1000 * Microsecond
const Millisecond = 1000 * Microsecond. Documented at pkg.go.dev, time.Millisecond.
field Heartbeat time.Duration
how often a quiet stream sends a comment
how often a quiet stream sends a comment field Heartbeat time.Duration. In ssebrowser/server.go, line 30.
const Second = 1000 * Millisecond
const Second = 1000 * Millisecond. Documented at pkg.go.dev, time.Second.
package http ("net/http")
Package http provides HTTP client and server implementations.
Package http provides HTTP client and server implementations. package http ("net/http"). Documented at pkg.go.dev, net/http.
type Server struct {
// Addr optionally specifies the TCP address for the server to listen on,
// in the form "host:port". If empty, ":http" (port 80) is used.
// The service names are defined in RFC 6335 and assigned by IANA.
// See net.Dial for details of the address format.
Addr string
Handler Handler // handler to invoke, http.DefaultServeMux if nil
// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
// ...
}
A Server defines parameters for running an HTTP server.
A Server defines parameters for running an HTTP server. type Server struct { // Addr optionally specifies the TCP address for the server to listen on, // in the form "host:port". If empty, ":http" (port 80) is used. // The service names are defined in RFC 6335 and assigned by IANA. // See net.Dial for details of the address format. Addr string Handler Handler // handler to invoke, http.DefaultServeMux if nil // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, // ... }. Documented at pkg.go.dev, net/http.Server.
field Handler Handler
handler to invoke, http.DefaultServeMux if nil
handler to invoke, http.DefaultServeMux if nil field Handler Handler. Documented at pkg.go.dev, net/http.Server.Handler.
func (s *Server) Handler() http.Handler
Handler returns the server's routes: the page at / and the event stream at /events?task=....
Handler returns the server's routes: the page at / and the event stream at /events?task=.... func (s *Server) Handler() http.Handler. In ssebrowser/server.go, line 36.
field ReadHeaderTimeout time.Duration
ReadHeaderTimeout is the amount of time allowed to read request headers.
net/http.Server.ReadHeaderTimeout
ReadHeaderTimeout is the amount of time allowed to read request headers. field ReadHeaderTimeout time.Duration. Documented at pkg.go.dev, net/http.Server.ReadHeaderTimeout.
field BaseContext func(net.Listener) context.Context
BaseContext optionally specifies a function that returns the base context for incoming requests on this server.
BaseContext optionally specifies a function that returns the base context for incoming requests on this server. field BaseContext func(net.Listener) context.Context. Documented at pkg.go.dev, net/http.Server.BaseContext.
package net ("net")
Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.
Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets. package net ("net"). Documented at pkg.go.dev, net.
type Listener interface {
// Accept waits for and returns the next connection to the listener.
Accept() (Conn, error)
// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors.
Close() error
// Addr returns the listener's network address.
Addr() Addr
}
A Listener is a generic network listener for stream-oriented protocols.
A Listener is a generic network listener for stream-oriented protocols. type Listener interface { // Accept waits for and returns the next connection to the listener. Accept() (Conn, error) // Close closes the listener. // Any blocked Accept operations will be unblocked and return errors. Close() error // Addr returns the listener's network address. Addr() Addr }. Documented at pkg.go.dev, net.Listener.
func new(TypeOrExpr) *Type
The built-in function new allocates a new, initialized variable and returns a pointer to it.
The built-in function new allocates a new, initialized variable and returns a pointer to it. func new(TypeOrExpr) *Type. Documented at pkg.go.dev, builtin.new.
type ListenConfig struct {
// If Control is not nil, it is called after creating the network
// connection but before binding it to the operating system.
//
// Network and address parameters passed to Control function are not
// necessarily the ones passed to Listen. Calling Listen with TCP networks
// will cause the Control function to be called with "tcp4" or "tcp6",
// UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6",
// and other known networks are passed as-is.
Control func(network, address string, c syscall.RawConn) error
// ...
}
ListenConfig contains options for listening to an address.
ListenConfig contains options for listening to an address. type ListenConfig struct { // If Control is not nil, it is called after creating the network // connection but before binding it to the operating system. // // Network and address parameters passed to Control function are not // necessarily the ones passed to Listen. Calling Listen with TCP networks // will cause the Control function to be called with "tcp4" or "tcp6", // UDP networks become "udp4" or "udp6", IP networks become "ip4" or "ip6", // and other known networks are passed as-is. Control func(network, address string, c syscall.RawConn) error // ... }. Documented at pkg.go.dev, net.ListenConfig.
func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error)
Listen announces on the local network address.
Listen announces on the local network address. func (lc *ListenConfig) Listen(ctx context.Context, network, address string) (Listener, error). Documented at pkg.go.dev, net.ListenConfig.Listen.
package fmt ("fmt")
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
Package fmt implements formatted I/O with functions analogous to C's printf and scanf. package fmt ("fmt"). Documented at pkg.go.dev, fmt.
func Fprintf(w io.Writer, format string, a ...any) (n int, err error)
Fprintf formats according to a format specifier and writes to w.
Fprintf formats according to a format specifier and writes to w. func Fprintf(w io.Writer, format string, a ...any) (n int, err error). Documented at pkg.go.dev, fmt.Fprintf.
func (Listener) Addr() Addr
Addr returns the listener's network address.
Addr returns the listener's network address. func (Listener) Addr() Addr. Documented at pkg.go.dev, net.Listener.Addr.
func (s *Server) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the server without interrupting any active connections.
Shutdown gracefully shuts down the server without interrupting any active connections. func (s *Server) Shutdown(ctx context.Context) error. Documented at pkg.go.dev, net/http.Server.Shutdown.

