Extensibility: Go SDK
Relevant source files
The following files were used as context for generating this wiki page:
The OpenCode Go SDK provides convenient, typed access to the OpenCode REST API from Go applications. It is generated using Stainless and designed to be highly extensible, allowing developers to go beyond the documented API features, customize request behavior, and integrate custom logic through middleware. This SDK is a key component for developers looking to build integrations or leverage OpenCode's capabilities within a Go environment.
The library requires Go 1.22+ for use. Most of the SDK code is generated, but modifications can be made, with the understanding that they might conflict with future generations. The lib/ and examples/ directories are never modified by the generator.
Sources: packages/sdk/go/README.md:1-17, packages/sdk/go/CONTRIBUTING.md:1-10
Client Initialization
The entry point to the SDK is the Client object. A basic client can be instantiated with default settings, but it can also be configured with various options at creation time using a functional options pattern.
// Default client
client := opencode.NewClient()
// Client with a custom header for all requests
clientWithOption := opencode.NewClient(
option.WithHeader("X-Some-Header", "custom_header_info"),
)
Sources: packages/sdk/go/README.md:24-30, 102-105
The diagram below shows the basic flow of initializing a client and making an API call.
This diagram illustrates the interaction between an application, the Go SDK, and the backend API for a typical request.
Sources: packages/sdk/go/README.md:24-30
Request and Response Handling
The SDK provides robust mechanisms for handling request parameters and parsing API responses, with a focus on distinguishing between zero values, nulls, and omitted fields.
Request Parameters
All request parameters are wrapped in a generic Field[T] type. This design choice ensures that the developer's intent is preserved, especially for optional parameters where a zero value (like 0, false, or "") might be a valid input.
Key helper functions for creating fields include:
opencode.F[T](https://github.com/sst/opencode/blob/HEAD/value): Creates a field with a given value.opencode.Null[T](https://github.com/sst/opencode/blob/HEAD/T): Creates a field that will be explicitly sent asnull.opencode.Raw[T](https://github.com/sst/opencode/blob/HEAD/any): Allows sending a value that doesn't conform to the expected type, useful for undocumented or evolving API features.
// Example of constructing request parameters
params := FooParams{
Name: opencode.F("hello"),
// Explicitly send "description": null
Description: opencode.Null[string](https://github.com/sst/opencode/blob/HEAD/string),
Point: opencode.F(opencode.Point{
X: opencode.Int(0), // Explicitly send 0
Y: opencode.Int(1),
}),
}
Sources: packages/sdk/go/README.md:36-60
Response Objects
Response structs contain value-type fields. If a field is null or not present in the API response, the corresponding struct field will hold its zero value. For more granular inspection, every response struct includes a JSON field.
The JSON field provides metadata about the response payload:
| Method | Description |
|---|---|
IsMissing() | Returns true if the key was not present in the JSON response. |
IsNull() | Returns true if the key was present but its value was null. |
IsInvalid() | Returns true if the API returned data that could not be coerced to the expected Go type. |
Raw() | Returns the raw json.RawMessage for the field. |
ExtraFields() | Returns a map of any properties in the JSON response not defined in the struct. |
This structure is crucial for extensibility, as it allows access to undocumented or new API response fields without waiting for an SDK update.
// Accessing an undocumented field from the response
body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
Sources: packages/sdk/go/README.md:62-99
Core Extensibility Features
The SDK is designed with several extension points that allow developers to customize and control its behavior.
Request Options
The functional options pattern (option package) is the primary way to modify individual requests or the client's default behavior.
The flow for applying request options is shown below:
This diagram shows how options provided at both the client and individual request level are merged to configure the final HTTP request.
Sources: packages/sdk/go/README.md:100-112
Commonly used options include:
| Option | Description |
|---|---|
option.WithHeader(key, value) | Adds or overrides an HTTP header. |
option.WithQuerySet(key, value) | Adds an undocumented query parameter. |
option.WithJSONSet(path, value) | Adds or sets a field in the JSON request body using sjson syntax. |
option.WithMaxRetries(n) | Configures the number of automatic retries for failed requests. |
option.WithRequestTimeout(d) | Sets a per-retry timeout. |
option.WithResponseInto(v) | Captures the raw *http.Response into a variable. |
option.WithMiddleware(m) | Applies custom middleware to the request. |
option.WithHTTPClient(c) | Replaces the default http.Client. |
Sources: packages/sdk/go/README.md:100-112, 166-173, 180-189, 214-233
Custom Middleware
Middleware allows for intercepting and transforming requests and responses. This is useful for custom logging, caching, or authentication schemes. A middleware function receives an *http.Request and a MiddlewareNext function to continue the chain.
This diagram shows how multiple middlewares are chained, with each one wrapping the next, before the request reaches the underlying HTTP transport.
Sources: packages/sdk/go/README.md:214-233
Undocumented API Access
The SDK provides escape hatches for interacting with API features that are not yet formally defined in the generated types.
-
Undocumented Endpoints: Use the generic HTTP verb methods on the client, such as
client.Post(),client.Get(), etc. These methods still respect client-level configurations like retries and headers.// Example of calling an undocumented endpoint var result *http.Response err := client.Post(context.Background(), "/unspecified_endpoint", params, &result)Sources: packages/sdk/go/README.md:195-205
-
Undocumented Request Parameters: Use
option.WithQuerySet()for query parameters oroption.WithJSONSet()for body parameters.// Example of adding an undocumented field to a request body client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))Sources: packages/sdk/go/README.md:207-212
-
Undocumented Response Properties: Access extra fields via the
res.JSON.ExtraFields()map.// Example of accessing an extra field extraValue := res.JSON.ExtraFields["new_field"].Raw()Sources: packages/sdk/go/README.md:94-99, 213
Development and Contribution
The Go SDK is an open-source component of OpenCode, and contributions are welcome.
- Setup: The environment can be bootstrapped using
./scripts/bootstrapand built with./scripts/build. - Testing: Tests require a mock server (like Prism) running against the OpenAPI spec. Tests can be executed with
./scripts/test. - Formatting: The project uses the standard
gofmtformatter, which can be run via./scripts/format. - Generated Code: As most of the code is generated, direct modifications may cause merge conflicts. New, non-generated code like examples should be placed in the
examples/directory.
Sources: packages/sdk/go/CONTRIBUTING.md
Summary
The OpenCode Go SDK is a powerful tool for Go developers, offering both the convenience of a fully-typed, generated library and the flexibility needed for real-world applications. Its core design, centered around the functional options pattern, middleware support, and transparent handling of undocumented API features, makes it highly extensible. This allows developers to tailor request behavior, inspect raw HTTP data, and interact with the latest API features without being blocked by SDK release cycles.