
encoding/json/v2 for LLM APIs in Go: what changed, and what an agent needs
What changed from encoding/json, and the parts of v2 an agent leans on, each checked in Go 1.27.
The whole loopEverything an agent says to a model API is JSON: the request, the reply, each tool’s definition, and the arguments of every tool call, which a model wrote and which are sometimes wrong.
Go’s newer JSON package, encoding/json/v2, with its lower-level companion encoding/json/jsontext, changes several defaults in ways that matter for exactly this kind of traffic.
This page covers what changed and the parts of the package an agent uses, with code from the companion repository, where it is tested.
Which Go has it
In Go 1.27, encoding/json/v2 is available by default; GOEXPERIMENT=nojsonv2 turns it off.
Go 1.26 ships it behind GOEXPERIMENT=jsonv2, and without that setting the package doesn’t build.
The original encoding/json is still there, so a program can move one package at a time.
The companion code needs Go 1.27, and go downloads it when it reads the module’s go.mod.
Why switch
For an agent, the case for v2 is mostly about what it refuses to accept. A model’s output is untrusted input, and v2’s defaults treat it that way:
- Duplicate keys are an error. In v1 the last one wins; when two parsers disagree about which duplicate counts, a value can get past a check that read the other one.
- Invalid UTF-8 is an error, in both directions, instead of passing through.
- Names match exactly, so
{"PATH": "..."}can’t land in a field taggedpathby accident.
The rest is control:
- Options per call, such as
RejectUnknownMembersfor strict tool arguments,AllowInvalidUTF8for tool output, andDeterministicfor stable bytes. v1’s only option of this kind wasDisallowUnknownFields, and only on aDecoder. - Marshalers for types you don’t own, passed with
WithMarshalersfor one call, instead of a wrapper type used everywhere. - Streaming marshalers,
MarshalJSONToandUnmarshalJSONFrom, which read and write token by token, so a field that can take two shapes needs no buffering or guessing. - Errors with locations:
SemanticErrorandSyntacticErrorcarry a JSON Pointer to the part of the input that failed, which is what a model needs to fix its arguments. - Zero values handled better:
omitzero, which respects anIsZeromethod, and nil slices written as[], which APIs that expect arrays prefer tonull.
It is also faster at decoding, though for an agent that hardly matters. On a MacBook Pro with an M1 Pro chip and Go 1.27, decoding into typed structs and encoding a request, five runs each:
| Payload | encoding/json |
encoding/json/v2 |
|---|---|---|
| a model’s reply, 3.8 KB | 9.7 to 10.4 µs | 7.2 to 8.5 µs |
| a 16-message request, 18 KB | 51 to 61 µs | 38 to 41 µs |
| encoding that request | 18.5 to 19.9 µs | 18.6 to 19.5 µs |
Decoding was about a quarter faster; encoding took the same time with both. A model call takes seconds, so tens of microseconds either way don’t change how long a run takes.
The costs are real too: code that relied on case-insensitive names or untagged fields stops decoding them, with no error; map keys are no longer sorted unless you ask; error text varies on purpose; and before Go 1.27 the package needs GOEXPERIMENT=jsonv2.
What changed, checked
Each row below was checked with a small program built with Go 1.27, decoding and encoding the same values with both packages:
| Input or value | encoding/json |
encoding/json/v2 |
|---|---|---|
{"TOOL_NAME": "x"} into a field tagged tool_name |
matches, ignoring case | doesn’t match; the field stays empty, with no error |
{"tool_name": "x"} into an untagged field ToolName |
matches | doesn’t match |
| a nil slice or map | null |
[] or {} |
omitempty on an int that is 0 |
left out | written as 0 |
| a string with invalid UTF-8 | accepted | an error, on encode and decode |
| the same key twice in an object | the last one wins | an error |
| an unknown key | ignored | ignored, unless RejectUnknownMembers is set |
| map keys | sorted | in no fixed order, unless Deterministic is set |
The first two rows cause the most trouble, because nothing reports them.
A reply field whose name differs in case from the tag, or a struct field with no tag at all, decodes as its zero value, and the program carries on with an empty string where the model’s answer should be.
The fix is a habit: every field decoded from an API or a model gets an explicit json tag with the exact wire name.
Wire types
These are the request and message types of a chat completions client.
Every field is tagged, and most use omitzero:
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
Tools []chatTool `json:"tools,omitzero"`
MaxTokens int `json:"max_tokens,omitzero"`
// Settings for asking about token probabilities (chapter 3).
Temperature *float64 `json:"temperature,omitzero"` // 0 is a setting
Logprobs bool `json:"logprobs,omitzero"`
TopLogprobs int `json:"top_logprobs,omitzero"`
Provider *routing `json:"provider,omitzero"`
// Streaming (chapter 6).
Stream bool `json:"stream,omitzero"`
StreamOptions *streamOptions `json:"stream_options,omitzero"`
}
// streamOptions asks for usage in the last chunk of a stream.
type streamOptions struct {
IncludeUsage bool `json:"include_usage"`
}
// routing tells OpenRouter which providers may serve a request.
type routing struct {
Only []string `json:"only,omitzero"`
RequireParameters bool `json:"require_parameters,omitzero"`
}
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content,omitzero"`
ToolCalls []chatToolCall `json:"tool_calls,omitzero"`
ToolCallID string `json:"tool_call_id,omitzero"`
ReasoningDetails jsontext.Value `json:"reasoning_details,omitzero"`
}
// chatToolCall is one tool call. The arguments are a string holding
// JSON, not a JSON object.
type chatToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // always "function"
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
omitzero leaves a field out when it holds its type’s zero value, which for an int is 0, the case omitempty no longer covers.
Without it, MaxTokens would go out as "max_tokens": 0 on every request, a request for an empty reply.
Where zero is a meaningful setting, the field is a pointer: Temperature is *float64, so “not set” is nil and a temperature of 0 is sent.
ReasoningDetails is a jsontext.Value, raw JSON kept exactly as it arrived.
Some models return reasoning that must be sent back unchanged on the next turn; the client never needs to know its structure, so it stores the bytes and writes them back as they were.
Text a tool printed: invalid UTF-8
A tool’s output goes into the next request, and tool output is whatever the tool printed: a test’s log, a file’s contents, a byte cut off partway through a character. v2 refuses to encode a string with invalid UTF-8, so one bad byte in a tool’s output would make the whole next request fail. The client encodes requests with one option that changes that:
func (c *Client) post(ctx context.Context,
wire chatRequest) (*http.Response, error) {
body, err := json.Marshal(wire, jsontext.AllowInvalidUTF8(true))
if err != nil {
return nil, fmt.Errorf("encode request: %w", err)
}
With jsontext.AllowInvalidUTF8(true), each invalid byte becomes the Unicode replacement character, U+FFFD, and the request goes out.
The same reasoning applies to code that truncates tool output to a size limit: cut at a character boundary, not at an arbitrary byte.
Tool arguments: strict, with errors the model can use
Tool arguments are the one place where an unknown field is a mistake rather than a newer API: a model that sends {"file": "a.go"} to a tool that takes path should be told so.
The agent decodes arguments with json.RejectUnknownMembers(true), and builds its own message from the error’s fields, because v2 deliberately varies the wording of its error messages between runs; the errors page shows that code.
Two error types carry the details: *jsontext.SyntacticError for JSON that isn’t valid, and *json.SemanticError for valid JSON that doesn’t fit the Go type, with a JSON Pointer to where it went wrong.
One field, two shapes
Model APIs often accept a field in more than one shape. A message’s content can be a plain string, or a list of parts, which is how a client marks a prompt-cache breakpoint, the point up to which the provider may cache the request. v2 lets one Go type handle that: it can write and read itself token by token, so it can look at the next value and decode it as whichever shape it is.
MarshalJSONTo writes through a *jsontext.Encoder, and UnmarshalJSONFrom reads from a *jsontext.Decoder:
// content is a message's text: a plain string, or, for a cache point
// with text, one text part carrying a cache_control marker, which
// OpenRouter passes on to providers that cache only where told. An
// empty cache point goes as a plain string; providers reject an empty
// text part.
type content struct {
Text string
Cache bool
}
type textPart struct {
Type string `json:"type"` // always "text"
Text string `json:"text"`
CacheControl *cacheControl `json:"cache_control,omitzero"`
}
type cacheControl struct {
Type string `json:"type"` // "ephemeral"
}
//nolint:wrapcheck // json/v2 wraps a marshaler's errors itself
func (c content) MarshalJSONTo(enc *jsontext.Encoder) error {
if !c.Cache || c.Text == "" {
return enc.WriteToken(jsontext.String(c.Text))
}
return json.MarshalEncode(enc, []textPart{{Type: "text", Text: c.Text,
CacheControl: &cacheControl{Type: "ephemeral"}}})
}
// IsZero reports whether there is no text, so omitzero leaves the
// content out whether or not the message is a cache point.
func (c content) IsZero() bool { return c.Text == "" }
// UnmarshalJSONFrom reads a reply's content: a string, null, or a list
// of parts, whose texts are joined.
func (c *content) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
v, err := dec.ReadValue()
if err != nil {
return err //nolint:wrapcheck // passed through to the decoder
}
switch v.Kind() {
case 'n':
*c = content{}
return nil
case '"':
return json.Unmarshal(v, &c.Text) //nolint:wrapcheck // as above
}
var parts []textPart
if err := json.Unmarshal(v, &parts); err != nil {
return err //nolint:wrapcheck // as above
}
var b strings.Builder
for _, p := range parts {
b.WriteString(p.Text)
}
*c = content{Text: b.String()}
return nil
}
The reader looks at the kind of the next value, 'n' for null, '"' for a string, anything else for a list, and decodes it accordingly.
The IsZero method matters too: omitzero calls it when a type has one, so a content with no text is left out of the message whatever else it holds.
Order you control
A JSON object’s members have no meaning in their order, but a model reads a tool’s schema top to bottom, so the order of its properties is worth keeping. A Go map can’t keep it, so the agent’s schema type holds the properties as a slice and writes them as an object, in order, token by token.
// props are an object's properties, in the order of the struct's
// fields. A Go map would lose that order, and the model reads the
// fields in the order the schema lists them.
type props []prop
type prop struct {
name string
s *schema
}
// MarshalJSONTo writes the properties as one JSON object, in order.
// encoding/json/v2 calls it for any type that has it. The encoder's
// errors pass through unchanged, so json/v2 can say where in the value
// encoding failed.
//
//nolint:wrapcheck // json/v2 wraps a marshaler's errors itself
func (ps props) MarshalJSONTo(enc *jsontext.Encoder) error {
if err := enc.WriteToken(jsontext.BeginObject); err != nil {
return err
}
for _, p := range ps {
if err := enc.WriteToken(jsontext.String(p.name)); err != nil {
return err
}
if err := json.MarshalEncode(enc, p.s); err != nil {
return err
}
}
return enc.WriteToken(jsontext.EndObject)
}
Same input, same bytes
v1 sorted map keys when it encoded a map; v2 doesn’t, unless asked.
Two things in an agent need the same input to encode to the same bytes every time: a hash, and a prompt cache, which providers match on an identical prefix of the request.
json.Deterministic(true) sorts map keys, and the agent uses it where the bytes are hashed, to detect a tool whose definition changed.
// Digest is a hash of everything a server says about a tool that
// reaches the model or decides how the tool runs: its name, title,
// description, schema, and annotations, as the server sent them. The
// schema is canonicalized first, so the same schema with its keys in
// another order hashes the same; any change to its text changes the
// digest.
func Digest(t mcp.ToolInfo) (string, error) {
schema := t.InputSchema.Clone()
if err := schema.Canonicalize(); err != nil {
return "", fmt.Errorf("tool %s: schema: %w", t.Name, err)
}
b, err := json.Marshal(struct {
Name string `json:"name"`
Title string `json:"title"`
Description string `json:"description"`
Schema jsontext.Value `json:"schema"`
Annotations *mcp.Annotations `json:"annotations"`
}{t.Name, t.Title, t.Description, schema, t.Annotations},
json.Deterministic(true))
if err != nil {
return "", fmt.Errorf("tool %s: %w", t.Name, err)
}
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:]), nil
}
Options for a whole format: saving a run
Options can be combined once and reused.
The agent’s checkpoint format (the file a run is saved to) joins three: leave zero fields out, write every jsontext.Value as a quoted string instead of as raw JSON, and read those strings back the same way.
The reason for the second is a model’s tool call.
Its arguments are meant to be JSON, and occasionally they aren’t.
A run that holds such a call still has to be saved, and raw invalid JSON can’t be embedded in a JSON file, while a string holding it can.
// format is how a checkpoint is written. Zero fields are left out, so
// a nil field loads as nil, not as an empty value. Every jsontext.Value
// is written as a string: a model's tool-call arguments can be invalid
// JSON, and a run that holds such a call must still be saved.
var format = json.JoinOptions(
json.OmitZeroStructFields(true),
json.WithMarshalers(json.MarshalFunc(
func(v jsontext.Value) ([]byte, error) {
//nolint:wrapcheck // json.Marshal wraps it
return jsontext.AppendQuote(nil, v)
})),
json.WithUnmarshalers(json.UnmarshalFunc(
func(b []byte, v *jsontext.Value) error {
s, err := jsontext.AppendUnquote(nil, b)
*v = s
return err //nolint:wrapcheck // json wraps it
})),
)
json.WithMarshalers and json.WithUnmarshalers apply these functions to every jsontext.Value in the checkpoint, without changing the type itself or any other code that encodes it.
Smaller things worth knowing
json:",inline"promotes a field’s members into the parent object. v2 already does this for an embedded struct without a JSON name, and the tag makes it explicit; it works on a named field too. The agent’s price table uses it so a long-prompt tier carries the same fields as the base price.json.MarshalWriteandjson.UnmarshalReadencode to anio.Writerand decode from anio.Reader.jsontext.Valuehas methods of its own:Kind,IsValid, andCanonicalize, which the tool digest above uses to put a schema in a standard form before hashing it.
Mistakes to avoid
- A decoded field without a tag. It matches only its exact Go name, and a miss is not an error.
omitemptyon a number or a bool. v2 writes 0 andfalse; useomitzero, or a pointer when zero is a real value.- Tool output encoded as it is. One invalid byte fails the next request; use
AllowInvalidUTF8, and truncate at character boundaries. - Matching v2’s error text. It changes between runs on purpose; inspect the error types instead.
- Maps in anything you hash or want cached. Use
Deterministic(true), or a slice that keeps the order. - Invalid model JSON stored as raw JSON. Store it as a string, or the save fails on exactly the run you most need to keep.
Try it
From the code directory of a clone of the companion repository:
$ go test ./ch06/openrouter -run 'TestGenerateSends|TestToolsOnTheWire' -v
- In
ch06/openrouter/wire.go, changeMaxTokens’s tag fromomitzerotoomitemptyand run the tests again: the request the client sends no longer matches the recorded one. - Remove the
jsontag from a field ofchatMessageand see which test fails, and how. - Encode a
map[string]inta few times with and withoutjson.Deterministic(true)and compare the output, using the small program below.
For the third, make a new directory, save this as main.go, run go mod init demo, edit the new go.mod so it says go 1.27, and run go run .:
package main
import (
"encoding/json/v2"
"fmt"
)
func main() {
m := map[string]int{"b": 2, "a": 1, "c": 3, "d": 4}
for range 3 {
out, _ := json.Marshal(m)
fmt.Println(string(out))
}
for range 3 {
out, _ := json.Marshal(m, json.Deterministic(true))
fmt.Println(string(out))
}
}
The first three lines list the keys in an order that can change from line to line (for example {"a":1,"c":3,"d":4,"b":2}, then {"b":2,"a":1,"c":3,"d":4}); the last three are always {"a":1,"b":2,"c":3,"d":4}.
type chatRequest struct {
Model string `json:"model"`
Messages []chatMessage `json:"messages"`
Tools []chatTool `json:"tools,omitzero"`
MaxTokens int `json:"max_tokens,omitzero"`
// Settings for asking about token probabilities (chapter 3).
Temperature *float64 `json:"temperature,omitzero"` // 0 is a setting
Logprobs bool `json:"logprobs,omitzero"`
TopLogprobs int `json:"top_logprobs,omitzero"`
// ...
}
type chatRequest struct { Model string `json:"model"` Messages []chatMessage `json:"messages"` Tools []chatTool `json:"tools,omitzero"` MaxTokens int `json:"max_tokens,omitzero"` // Settings for asking about token probabilities (chapter 3). Temperature *float64 `json:"temperature,omitzero"` // 0 is a setting Logprobs bool `json:"logprobs,omitzero"` TopLogprobs int `json:"top_logprobs,omitzero"` // ... }. In ch06/openrouter/wire.go, line 15.
field Model string `json:"model"`
field Model string `json:"model"`. In ch06/openrouter/wire.go, line 16.
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.
field Messages []chatMessage `json:"messages"`
field Messages []chatMessage `json:"messages"`. In ch06/openrouter/wire.go, line 17.
type chatMessage struct {
Role string `json:"role"`
Content string `json:"content,omitzero"`
ToolCalls []chatToolCall `json:"tool_calls,omitzero"`
ToolCallID string `json:"tool_call_id,omitzero"`
ReasoningDetails jsontext.Value `json:"reasoning_details,omitzero"`
}
type chatMessage struct { Role string `json:"role"` Content string `json:"content,omitzero"` ToolCalls []chatToolCall `json:"tool_calls,omitzero"` ToolCallID string `json:"tool_call_id,omitzero"` ReasoningDetails jsontext.Value `json:"reasoning_details,omitzero"` }. In ch06/openrouter/wire.go, line 64.
field Tools []chatTool `json:"tools,omitzero"`
field Tools []chatTool `json:"tools,omitzero"`. In ch06/openrouter/wire.go, line 18.
type chatTool struct {
Type string `json:"type"` // always "function"
Function chatFunction `json:"function"`
}
chatTool is a tool definition.
chatTool is a tool definition. type chatTool struct { Type string `json:"type"` // always "function" Function chatFunction `json:"function"` }. In ch06/openrouter/wire.go, line 49.
field MaxTokens int `json:"max_tokens,omitzero"`
field MaxTokens int `json:"max_tokens,omitzero"`. In ch06/openrouter/wire.go, line 19.
type int int
int is a signed integer type that is at least 32 bits in size.
int is a signed integer type that is at least 32 bits in size. type int int. Documented at pkg.go.dev, builtin.int.
field Temperature *float64 `json:"temperature,omitzero"`
Settings for asking about token probabilities (chapter 3).
Settings for asking about token probabilities (chapter 3). field Temperature *float64 `json:"temperature,omitzero"`. In ch06/openrouter/wire.go, line 22.
type float64 float64
float64 is the set of all IEEE 754 64-bit floating-point numbers.
float64 is the set of all IEEE 754 64-bit floating-point numbers. type float64 float64. Documented at pkg.go.dev, builtin.float64.
field Logprobs bool `json:"logprobs,omitzero"`
field Logprobs bool `json:"logprobs,omitzero"`. In ch06/openrouter/wire.go, line 23.
type bool bool
bool is the set of boolean values, true and false.
bool is the set of boolean values, true and false. type bool bool. Documented at pkg.go.dev, builtin.bool.
field TopLogprobs int `json:"top_logprobs,omitzero"`
field TopLogprobs int `json:"top_logprobs,omitzero"`. In ch06/openrouter/wire.go, line 24.
field Provider *routing `json:"provider,omitzero"`
field Provider *routing `json:"provider,omitzero"`. In ch06/openrouter/wire.go, line 25.
type routing struct {
Only []string `json:"only,omitzero"`
RequireParameters bool `json:"require_parameters,omitzero"`
}
routing tells OpenRouter which providers may serve a request.
routing tells OpenRouter which providers may serve a request. type routing struct { Only []string `json:"only,omitzero"` RequireParameters bool `json:"require_parameters,omitzero"` }. In ch06/openrouter/wire.go, line 38.
field Stream bool `json:"stream,omitzero"`
Streaming (chapter 6).
Streaming (chapter 6). field Stream bool `json:"stream,omitzero"`. In ch06/openrouter/wire.go, line 28.
field StreamOptions *streamOptions `json:"stream_options,omitzero"`
field StreamOptions *streamOptions `json:"stream_options,omitzero"`. In ch06/openrouter/wire.go, line 29.
type streamOptions struct {
IncludeUsage bool `json:"include_usage"`
}
streamOptions asks for usage in the last chunk of a stream.
streamOptions asks for usage in the last chunk of a stream. type streamOptions struct { IncludeUsage bool `json:"include_usage"` }. In ch06/openrouter/wire.go, line 33.
field IncludeUsage bool `json:"include_usage"`
field IncludeUsage bool `json:"include_usage"`. In ch06/openrouter/wire.go, line 34.
field Only []string `json:"only,omitzero"`
field Only []string `json:"only,omitzero"`. In ch06/openrouter/wire.go, line 39.
field RequireParameters bool `json:"require_parameters,omitzero"`
field RequireParameters bool `json:"require_parameters,omitzero"`. In ch06/openrouter/wire.go, line 40.
field Role string `json:"role"`
field Role string `json:"role"`. In ch06/openrouter/wire.go, line 65.
field Content string `json:"content,omitzero"`
field Content string `json:"content,omitzero"`. In ch06/openrouter/wire.go, line 66.
field ToolCalls []chatToolCall `json:"tool_calls,omitzero"`
field ToolCalls []chatToolCall `json:"tool_calls,omitzero"`. In ch06/openrouter/wire.go, line 67.
type chatToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // always "function"
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
chatToolCall is one tool call.
chatToolCall is one tool call. type chatToolCall struct { ID string `json:"id"` Type string `json:"type"` // always "function" Function struct { Name string `json:"name"` Arguments string `json:"arguments"` } `json:"function"` }. In ch06/openrouter/wire.go, line 74.
field ToolCallID string `json:"tool_call_id,omitzero"`
field ToolCallID string `json:"tool_call_id,omitzero"`. In ch06/openrouter/wire.go, line 68.
field ReasoningDetails jsontext.Value `json:"reasoning_details,omitzero"`
field ReasoningDetails jsontext.Value `json:"reasoning_details,omitzero"`. In ch06/openrouter/wire.go, line 69.
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.
type Value []byte
Value represents a single raw JSON value, which may be one of the following:
Value represents a single raw JSON value, which may be one of the following: type Value []byte. Documented at pkg.go.dev, encoding/json/jsontext.Value.
field ID string `json:"id"`
field ID string `json:"id"`. In ch06/openrouter/wire.go, line 75.
field Type string `json:"type"`
always "function"
always "function" field Type string `json:"type"`. In ch06/openrouter/wire.go, line 76.
field Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
field Function struct { Name string `json:"name"` Arguments string `json:"arguments"` } `json:"function"`. In ch06/openrouter/wire.go, line 77.
field Arguments string
field Arguments string. In ch06/openrouter/wire.go, line 79.
type Client struct {
BaseURL string // DefaultBaseURL if empty
APIKey string // sent as a bearer token
Model string // a model ID from OpenRouter's list
HTTP *http.Client // http.DefaultClient if nil
Timeout time.Duration // per Generate call; 2 minutes if zero
// IdleTimeout is the longest a stream may go without sending a
// byte, including the wait for its headers; 30 seconds if zero
// (chapter 6). Stream doesn't use Timeout.
// ...
}
Client calls a model through OpenRouter.
Client calls a model through OpenRouter. type Client struct { BaseURL string // DefaultBaseURL if empty APIKey string // sent as a bearer token Model string // a model ID from OpenRouter's list HTTP *http.Client // http.DefaultClient if nil Timeout time.Duration // per Generate call; 2 minutes if zero // IdleTimeout is the longest a stream may go without sending a // byte, including the wait for its headers; 30 seconds if zero // (chapter 6). Stream doesn't use Timeout. // ... }. In ch06/openrouter/client.go, line 40.
func (c *Client) post(ctx context.Context,
wire chatRequest) (*http.Response, error)
post sends a request to the chat completions endpoint and returns the response, whatever its status.
post sends a request to the chat completions endpoint and returns the response, whatever its status. func (c *Client) post(ctx context.Context, wire chatRequest) (*http.Response, error). In ch06/openrouter/client.go, line 88.
var ctx context.Context
var ctx context.Context. In ch06/openrouter/client.go, line 88.
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.
var wire chatRequest
var wire chatRequest. In ch06/openrouter/client.go, line 89.
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 Response struct {
Status string // e.g. "200 OK"
StatusCode int // e.g. 200
Proto string // e.g. "HTTP/1.0"
ProtoMajor int // e.g. 1
ProtoMinor int // e.g. 0
// Header maps header keys to values. If the response had multiple
// headers with the same key, they may be concatenated, with comma
// delimiters. (RFC 7230, section 3.2.2 requires that multiple headers
// ...
}
Response represents the response from an HTTP request.
Response represents the response from an HTTP request. type Response struct { Status string // e.g. "200 OK" StatusCode int // e.g. 200 Proto string // e.g. "HTTP/1.0" ProtoMajor int // e.g. 1 ProtoMinor int // e.g. 0 // Header maps header keys to values. If the response had multiple // headers with the same key, they may be concatenated, with comma // delimiters. (RFC 7230, section 3.2.2 requires that multiple headers // ... }. Documented at pkg.go.dev, net/http.Response.
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.
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.
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 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.
type content struct {
Text string
Cache bool
}
content is a message's text: a plain string, or, for a cache point with text, one text part carrying a cache_control marker, which OpenRouter passes on to providers that cache only where told.
content is a message's text: a plain string, or, for a cache point with text, one text part carrying a cache_control marker, which OpenRouter passes on to providers that cache only where told. type content struct { Text string Cache bool }. In ch12/openrouter/wire.go, line 111.
field Text string
field Text string. In ch12/openrouter/wire.go, line 112.
type textPart struct {
Type string `json:"type"` // always "text"
Text string `json:"text"`
CacheControl *cacheControl `json:"cache_control,omitzero"`
}
type textPart struct { Type string `json:"type"` // always "text" Text string `json:"text"` CacheControl *cacheControl `json:"cache_control,omitzero"` }. In ch12/openrouter/wire.go, line 116.
field Type string `json:"type"`
always "text"
always "text" field Type string `json:"type"`. In ch12/openrouter/wire.go, line 117.
field Text string `json:"text"`
field Text string `json:"text"`. In ch12/openrouter/wire.go, line 118.
field CacheControl *cacheControl `json:"cache_control,omitzero"`
field CacheControl *cacheControl `json:"cache_control,omitzero"`. In ch12/openrouter/wire.go, line 119.
type cacheControl struct {
Type string `json:"type"` // "ephemeral"
}
type cacheControl struct { Type string `json:"type"` // "ephemeral" }. In ch12/openrouter/wire.go, line 122.
field Type string `json:"type"`
"ephemeral"
"ephemeral" field Type string `json:"type"`. In ch12/openrouter/wire.go, line 123.
func (c content) MarshalJSONTo(enc *jsontext.Encoder) error
func (c content) MarshalJSONTo(enc *jsontext.Encoder) error. In ch12/openrouter/wire.go, line 127.
var enc *jsontext.Encoder
var enc *jsontext.Encoder. In ch12/openrouter/wire.go, line 127.
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.
type Encoder struct {
s encoderState
}
Encoder is a streaming encoder to raw JSON tokens and values.
encoding/json/jsontext.Encoder
Encoder is a streaming encoder to raw JSON tokens and values. type Encoder struct { s encoderState }. Documented at pkg.go.dev, encoding/json/jsontext.Encoder.
func (e *Encoder) WriteToken(t Token) error
WriteToken writes the next token and advances the internal write offset.
encoding/json/jsontext.Encoder.WriteToken
WriteToken writes the next token and advances the internal write offset. func (e *Encoder) WriteToken(t Token) error. Documented at pkg.go.dev, encoding/json/jsontext.Encoder.WriteToken.
func String(s string) Token
String constructs a Token representing a JSON string.
String constructs a Token representing a JSON string. func String(s string) Token. Documented at pkg.go.dev, encoding/json/jsontext.String.
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 MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) (err error)
MarshalEncode serializes a Go value into an [jsontext.Encoder] according to the provided marshal or encode options (while ignoring unmarshal or decode options).
encoding/json/v2.MarshalEncode
MarshalEncode serializes a Go value into an [jsontext.Encoder] according to the provided marshal or encode options (while ignoring unmarshal or decode options). func MarshalEncode(out *jsontext.Encoder, in any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.MarshalEncode.
func (c content) IsZero() bool
IsZero reports whether there is no text, so omitzero leaves the content out whether or not the message is a cache point.
IsZero reports whether there is no text, so omitzero leaves the content out whether or not the message is a cache point. func (c content) IsZero() bool. In ch12/openrouter/wire.go, line 139.
func (c *content) UnmarshalJSONFrom(dec *jsontext.Decoder) error
UnmarshalJSONFrom reads a reply's content: a string, null, or a list of parts, whose texts are joined.
UnmarshalJSONFrom reads a reply's content: a string, null, or a list of parts, whose texts are joined. func (c *content) UnmarshalJSONFrom(dec *jsontext.Decoder) error. In ch12/openrouter/wire.go, line 143.
var dec *jsontext.Decoder
var dec *jsontext.Decoder. In ch12/openrouter/wire.go, line 143.
type Decoder struct {
s decoderState
}
Decoder is a streaming decoder for raw JSON tokens and values.
encoding/json/jsontext.Decoder
Decoder is a streaming decoder for raw JSON tokens and values. type Decoder struct { s decoderState }. Documented at pkg.go.dev, encoding/json/jsontext.Decoder.
var v jsontext.Value
var v jsontext.Value. In ch12/openrouter/wire.go, line 144.
func (d *Decoder) ReadValue() (Value, error)
ReadValue returns the next raw JSON value, advancing the read offset.
encoding/json/jsontext.Decoder.ReadValue
ReadValue returns the next raw JSON value, advancing the read offset. func (d *Decoder) ReadValue() (Value, error). Documented at pkg.go.dev, encoding/json/jsontext.Decoder.ReadValue.
func (v Value) Kind() Kind
Kind returns the starting token kind.
encoding/json/jsontext.Value.Kind
Kind returns the starting token kind. func (v Value) Kind() Kind. Documented at pkg.go.dev, encoding/json/jsontext.Value.Kind.
func Unmarshal(in []byte, out any, opts ...Options) (err error)
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options).
Unmarshal decodes a []byte input into a Go value according to the provided unmarshal and decode options (while ignoring marshal or encode options). func Unmarshal(in []byte, out any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.Unmarshal.
var parts []textPart
var parts []textPart. In ch12/openrouter/wire.go, line 155.
var b strings.Builder
var b strings.Builder. In ch12/openrouter/wire.go, line 159.
package strings ("strings")
Package strings implements simple functions to manipulate UTF-8 encoded strings.
Package strings implements simple functions to manipulate UTF-8 encoded strings. package strings ("strings"). Documented at pkg.go.dev, strings.
type Builder struct {
addr *Builder // of receiver, to detect copies by value
// External users should never get direct access to this buffer, since
// the slice at some point will be converted to a string using unsafe, also
// data between len(buf) and cap(buf) might be uninitialized.
buf []byte
}
A Builder is used to efficiently build a string using [Builder.Write] methods.
A Builder is used to efficiently build a string using [Builder.Write] methods. type Builder struct { addr *Builder // of receiver, to detect copies by value // External users should never get direct access to this buffer, since // the slice at some point will be converted to a string using unsafe, also // data between len(buf) and cap(buf) might be uninitialized. buf []byte }. Documented at pkg.go.dev, strings.Builder.
func (b *Builder) WriteString(s string) (int, error)
WriteString appends the contents of s to b's buffer.
WriteString appends the contents of s to b's buffer. func (b *Builder) WriteString(s string) (int, error). Documented at pkg.go.dev, strings.Builder.WriteString.
func (b *Builder) String() string
String returns the accumulated string.
String returns the accumulated string. func (b *Builder) String() string. Documented at pkg.go.dev, strings.Builder.String.
type props []prop
props are an object's properties, in the order of the struct's fields.
props are an object's properties, in the order of the struct's fields. type props []prop. In ch12/agent/schema.go, line 37.
type prop struct {
name string
s *schema
}
type prop struct { name string s *schema }. In ch12/agent/schema.go, line 39.
type schema struct {
Type string `json:"type"`
Description string `json:"description,omitzero"`
Enum []string `json:"enum,omitzero"`
Items *schema `json:"items,omitzero"`
Properties props `json:"properties,omitzero"`
Required []string `json:"required,omitzero"`
NoExtras *bool `json:"additionalProperties,omitzero"`
optional bool // the field may be left out (omitzero in its json tag)
field int // the struct field index, for properties
}
A schema is the subset of JSON Schema the book generates: the types a tool's arguments can have, with no field the struct doesn't list.
A schema is the subset of JSON Schema the book generates: the types a tool's arguments can have, with no field the struct doesn't list. type schema struct { Type string `json:"type"` Description string `json:"description,omitzero"` Enum []string `json:"enum,omitzero"` Items *schema `json:"items,omitzero"` Properties props `json:"properties,omitzero"` Required []string `json:"required,omitzero"` NoExtras *bool `json:"additionalProperties,omitzero"` optional bool // the field may be left out (omitzero in its json tag) field int // the struct field index, for properties }. In ch12/agent/schema.go, line 17.
func (ps props) MarshalJSONTo(enc *jsontext.Encoder) error
MarshalJSONTo writes the properties as one JSON object, in order.
MarshalJSONTo writes the properties as one JSON object, in order. func (ps props) MarshalJSONTo(enc *jsontext.Encoder) error. In ch12/agent/schema.go, line 50.
var enc *jsontext.Encoder
var enc *jsontext.Encoder. In ch12/agent/schema.go, line 50.
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.
var BeginObject Token = rawToken("{")
encoding/json/jsontext.BeginObject
var BeginObject Token = rawToken("{"). Documented at pkg.go.dev, encoding/json/jsontext.BeginObject.
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.
var EndObject Token = rawToken("}")
encoding/json/jsontext.EndObject
var EndObject Token = rawToken("}"). Documented at pkg.go.dev, encoding/json/jsontext.EndObject.
func Digest(t mcp.ToolInfo) (string, error)
Digest is a hash of everything a server says about a tool that reaches the model or decides how the tool runs: its name, title, description, schema, and annotations, as the server sent them.
Digest is a hash of everything a server says about a tool that reaches the model or decides how the tool runs: its name, title, description, schema, and annotations, as the server sent them. func Digest(t mcp.ToolInfo) (string, error). In ch10/mcptools/trust.go, line 139.
var t mcp.ToolInfo
var t mcp.ToolInfo. In ch10/mcptools/trust.go, line 139.
package mcp ("github.com/blackwell-systems/go-agents-book/code/ch10/mcp")
Package mcp is the Model Context Protocol over standard input and output, written by hand: newline-delimited JSON-RPC 2.0 messages, a server that offers tools, and a client that calls them (chapter 10).
Package mcp is the Model Context Protocol over standard input and output, written by hand: newline-delimited JSON-RPC 2.0 messages, a server that offers tools, and a client that calls them (chapter 10). package mcp ("github.com/blackwell-systems/go-agents-book/code/ch10/mcp"). In ch10/mcp.
type ToolInfo struct {
Name string `json:"name"`
Title string `json:"title,omitzero"`
Description string `json:"description,omitzero"`
InputSchema jsontext.Value `json:"inputSchema"`
Annotations *Annotations `json:"annotations,omitzero"`
}
A ToolInfo is one tool as a server describes it in tools/list.
A ToolInfo is one tool as a server describes it in tools/list. type ToolInfo struct { Name string `json:"name"` Title string `json:"title,omitzero"` Description string `json:"description,omitzero"` InputSchema jsontext.Value `json:"inputSchema"` Annotations *Annotations `json:"annotations,omitzero"` }. In ch10/mcp/protocol.go, line 68.
var schema jsontext.Value
var schema jsontext.Value. In ch10/mcptools/trust.go, line 140.
field InputSchema jsontext.Value `json:"inputSchema"`
field InputSchema jsontext.Value `json:"inputSchema"`. In ch10/mcp/protocol.go, line 72.
func (v Value) Clone() Value
Clone returns a copy of v.
encoding/json/jsontext.Value.Clone
Clone returns a copy of v. func (v Value) Clone() Value. Documented at pkg.go.dev, encoding/json/jsontext.Value.Clone.
func (v *Value) Canonicalize(opts ...Options) error
Canonicalize canonicalizes the raw JSON value according to the JSON Canonicalization Scheme (JCS) as defined by RFC 8785.
encoding/json/jsontext.Value.Canonicalize
Canonicalize canonicalizes the raw JSON value according to the JSON Canonicalization Scheme (JCS) as defined by RFC 8785. func (v *Value) Canonicalize(opts ...Options) error. Documented at pkg.go.dev, encoding/json/jsontext.Value.Canonicalize.
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.
field Name string `json:"name"`
field Name string `json:"name"`. In ch10/mcp/protocol.go, line 69.
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.
field Title string
field Title string. In ch10/mcptools/trust.go, line 146.
field Description string
field Description string. In ch10/mcptools/trust.go, line 147.
field Schema jsontext.Value
field Schema jsontext.Value. In ch10/mcptools/trust.go, line 148.
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.
field Annotations *mcp.Annotations
field Annotations *mcp.Annotations. In ch10/mcptools/trust.go, line 149.
type Annotations struct {
ReadOnly *bool `json:"readOnlyHint,omitzero"`
Destructive *bool `json:"destructiveHint,omitzero"`
Idempotent *bool `json:"idempotentHint,omitzero"`
OpenWorld *bool `json:"openWorldHint,omitzero"`
}
Annotations are a server's hints about a tool's behavior.
Annotations are a server's hints about a tool's behavior. type Annotations struct { ReadOnly *bool `json:"readOnlyHint,omitzero"` Destructive *bool `json:"destructiveHint,omitzero"` Idempotent *bool `json:"idempotentHint,omitzero"` OpenWorld *bool `json:"openWorldHint,omitzero"` }. In ch10/mcp/protocol.go, line 79.
field Title string `json:"title,omitzero"`
field Title string `json:"title,omitzero"`. In ch10/mcp/protocol.go, line 70.
field Description string `json:"description,omitzero"`
field Description string `json:"description,omitzero"`. In ch10/mcp/protocol.go, line 71.
field Annotations *Annotations `json:"annotations,omitzero"`
field Annotations *Annotations `json:"annotations,omitzero"`. In ch10/mcp/protocol.go, line 73.
func Deterministic(v bool) Options
Deterministic specifies that marshaling the same input value will always serialize as the same output bytes.
encoding/json/v2.Deterministic
Deterministic specifies that marshaling the same input value will always serialize as the same output bytes. func Deterministic(v bool) Options. Documented at pkg.go.dev, encoding/json/v2.Deterministic.
package sha256 ("crypto/sha256")
Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4.
Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4. package sha256 ("crypto/sha256"). Documented at pkg.go.dev, crypto/sha256.
func Sum256(data []byte) [Size]byte
Sum256 returns the SHA256 checksum of the data.
Sum256 returns the SHA256 checksum of the data. func Sum256(data []byte) [Size]byte. Documented at pkg.go.dev, crypto/sha256.Sum256.
package hex ("encoding/hex")
Package hex implements hexadecimal encoding and decoding.
Package hex implements hexadecimal encoding and decoding. package hex ("encoding/hex"). Documented at pkg.go.dev, encoding/hex.
func EncodeToString(src []byte) string
EncodeToString returns the hexadecimal encoding of src.
EncodeToString returns the hexadecimal encoding of src. func EncodeToString(src []byte) string. Documented at pkg.go.dev, encoding/hex.EncodeToString.
var format = json.JoinOptions( ...
format is how a checkpoint is written.
ch15/durable/checkpoint.go:191
format is how a checkpoint is written. var format = json.JoinOptions( .... In ch15/durable/checkpoint.go, line 191.
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 JoinOptions(srcs ...Options) Options
JoinOptions coalesces the provided list of options into a single Options.
JoinOptions coalesces the provided list of options into a single Options. func JoinOptions(srcs ...Options) Options. Documented at pkg.go.dev, encoding/json/v2.JoinOptions.
func OmitZeroStructFields(v bool) Options
OmitZeroStructFields specifies that zero-valued fields of Go struct should be omitted from the marshaled output.
encoding/json/v2.OmitZeroStructFields
OmitZeroStructFields specifies that zero-valued fields of Go struct should be omitted from the marshaled output. func OmitZeroStructFields(v bool) Options. Documented at pkg.go.dev, encoding/json/v2.OmitZeroStructFields.
func WithMarshalers(v *Marshalers) Options
WithMarshalers specifies a list of type-specific marshalers to use, which can be used to override the default marshal behavior for values of particular types.
encoding/json/v2.WithMarshalers
WithMarshalers specifies a list of type-specific marshalers to use, which can be used to override the default marshal behavior for values of particular types. func WithMarshalers(v *Marshalers) Options. Documented at pkg.go.dev, encoding/json/v2.WithMarshalers.
func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers
MarshalFunc constructs a type-specific marshaler that specifies how to marshal values of type T. T can be any type except a named pointer.
MarshalFunc constructs a type-specific marshaler that specifies how to marshal values of type T. T can be any type except a named pointer. func MarshalFunc[T any](fn func(T) ([]byte, error)) *Marshalers. Documented at pkg.go.dev, encoding/json/v2.MarshalFunc.
var v jsontext.Value
ch15/durable/checkpoint.go:194
var v jsontext.Value. In ch15/durable/checkpoint.go, line 194.
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.
type byte = uint8
byte is an alias for uint8 and is equivalent to uint8 in all ways.
byte is an alias for uint8 and is equivalent to uint8 in all ways. type byte = uint8. Documented at pkg.go.dev, builtin.byte.
func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error)
AppendQuote appends a double-quoted JSON string literal representing src to dst and returns the extended buffer.
encoding/json/jsontext.AppendQuote
AppendQuote appends a double-quoted JSON string literal representing src to dst and returns the extended buffer. func AppendQuote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error). Documented at pkg.go.dev, encoding/json/jsontext.AppendQuote.
func WithUnmarshalers(v *Unmarshalers) Options
WithUnmarshalers specifies a list of type-specific unmarshalers to use, which can be used to override the default unmarshal behavior for values of particular types.
encoding/json/v2.WithUnmarshalers
WithUnmarshalers specifies a list of type-specific unmarshalers to use, which can be used to override the default unmarshal behavior for values of particular types. func WithUnmarshalers(v *Unmarshalers) Options. Documented at pkg.go.dev, encoding/json/v2.WithUnmarshalers.
func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers
UnmarshalFunc constructs a type-specific unmarshaler that specifies how to unmarshal values of type T. T must be an unnamed pointer or an interface type.
encoding/json/v2.UnmarshalFunc
UnmarshalFunc constructs a type-specific unmarshaler that specifies how to unmarshal values of type T. T must be an unnamed pointer or an interface type. func UnmarshalFunc[T any](fn func([]byte, T) error) *Unmarshalers. Documented at pkg.go.dev, encoding/json/v2.UnmarshalFunc.
var v *jsontext.Value
ch15/durable/checkpoint.go:199
var v *jsontext.Value. In ch15/durable/checkpoint.go, line 199.
func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error)
AppendUnquote appends the decoded interpretation of src as a double-quoted JSON string literal to dst and returns the extended buffer.
encoding/json/jsontext.AppendUnquote
AppendUnquote appends the decoded interpretation of src as a double-quoted JSON string literal to dst and returns the extended buffer. func AppendUnquote[Bytes ~[]byte | ~string](dst []byte, src Bytes) ([]byte, error). Documented at pkg.go.dev, encoding/json/jsontext.AppendUnquote.
func RejectUnknownMembers(v bool) Options
RejectUnknownMembers specifies that unknown members should be rejected when unmarshaling a JSON object.
encoding/json/v2.RejectUnknownMembers
RejectUnknownMembers specifies that unknown members should be rejected when unmarshaling a JSON object. func RejectUnknownMembers(v bool) Options. Documented at pkg.go.dev, encoding/json/v2.RejectUnknownMembers.
type SyntacticError struct {
requireKeyedLiterals
nonComparable
// ByteOffset indicates that an error occurred at or after this byte offset.
ByteOffset int64
// JSONPointer indicates that an error occurred within this JSON value
// as indicated using the JSON Pointer notation (see RFC 6901).
JSONPointer Pointer
// ...
}
SyntacticError is a description of an error that occurred when encoding or decoding JSON according to the grammar.
encoding/json/jsontext.SyntacticError
SyntacticError is a description of an error that occurred when encoding or decoding JSON according to the grammar. type SyntacticError struct { requireKeyedLiterals nonComparable // ByteOffset indicates that an error occurred at or after this byte offset. ByteOffset int64 // JSONPointer indicates that an error occurred within this JSON value // as indicated using the JSON Pointer notation (see RFC 6901). JSONPointer Pointer // ... }. Documented at pkg.go.dev, encoding/json/jsontext.SyntacticError.
type SemanticError struct {
requireKeyedLiterals
nonComparable
action string // either "marshal" or "unmarshal"
// ByteOffset indicates that an error occurred at or after this byte offset.
ByteOffset int64
// JSONPointer indicates that an error occurred within this JSON value
// as indicated using the JSON Pointer notation (see RFC 6901).
// ...
}
SemanticError describes an error determining the meaning of JSON data as Go data, or vice versa.
encoding/json/v2.SemanticError
SemanticError describes an error determining the meaning of JSON data as Go data, or vice versa. type SemanticError struct { requireKeyedLiterals nonComparable action string // either "marshal" or "unmarshal" // ByteOffset indicates that an error occurred at or after this byte offset. ByteOffset int64 // JSONPointer indicates that an error occurred within this JSON value // as indicated using the JSON Pointer notation (see RFC 6901). // ... }. Documented at pkg.go.dev, encoding/json/v2.SemanticError.
func MarshalWrite(out io.Writer, in any, opts ...Options) (err error)
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options).
MarshalWrite serializes a Go value into an io.Writer according to the provided marshal and encode options (while ignoring unmarshal or decode options). func MarshalWrite(out io.Writer, in any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.MarshalWrite.
func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error)
UnmarshalRead deserializes a Go value from an io.Reader according to the provided unmarshal and decode options (while ignoring marshal or encode options).
encoding/json/v2.UnmarshalRead
UnmarshalRead deserializes a Go value from an io.Reader according to the provided unmarshal and decode options (while ignoring marshal or encode options). func UnmarshalRead(in io.Reader, out any, opts ...Options) (err error). Documented at pkg.go.dev, encoding/json/v2.UnmarshalRead.