> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Go

> Call an app from Go with a client generated from its contract

The Go client is the runtime package
`github.com/bijectionhq/bijection/sdks/application/go/bijection` plus a
package that `bijection client go` generates from your app's contract. The
generated package names every exposed function as a typed ref and pins the
contract, and the runtime runs the calls.

## Install

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
go get github.com/bijectionhq/bijection/sdks/application/go@v0.10.0
```

The runtime uses only the standard library. It needs Go 1.22 or later.

## Generate a client

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection client go --out ordersclient --name github.com/acme/ordersclient
```

`--name` is the module path. The command reads the app's exposed tree and the
`contract` line of the committed `bijection.lock`, and refuses when that line
differs from the source's (run `bijection check --write-lock` first). It writes:

| File | Holds |
| - | - |
| `client.go` | `Contract` and `Connect`, which pins it. |
| `app.go` | `App`, the exposed tree: one `bijection.QueryRef` or `bijection.MutationRef` per function, at its tree path. |
| `types.go` | A struct for each argument and value object, and a named string type for each set of literal values. |
| `interface.json` | The language-neutral interface document. |

Generate the package again when the app's exposed functions change. Do not
edit it.

## Connect

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import (
	"github.com/acme/ordersclient"
	"github.com/bijectionhq/bijection/sdks/application/go/bijection"
)

client, err := ordersclient.Connect("https://orders.example.com", bijection.Options{Token: token})
if err != nil {
	return err
}
defer client.Close()
```

| Option | Meaning |
| - | - |
| `Token` | A fixed credential, sent as `Authorization: Bearer`. Leave it out to call anonymously. |
| `TokenSource` | A function asked for the current credential on every call and live connection (`refresh` asks for a new one). |
| `Contract` | The app contract. The generated `Connect` sets it. |
| `Headers` | Headers added to every call and to the live connection's handshake. |
| `HTTPClient` | The `*http.Client` calls use. |

An installation whose contract differs from the pinned one refuses every call
with `Conflict`, and the message starts with `ContractStale`. Generate the
client again against the deployed app.

For a dynamic tool, the raw connector uses `bijection.Options{Discover: true}`. A pinned client refuses a path absent from its contract map before sending it.

## Calls

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
recent := bijection.Query(ctx, client, ordersclient.App.Orders.Recent,
	ordersclient.OrdersRecentArgs{Customer: "c-1"})
if !recent.OK {
	return fmt.Errorf("%s: %s", recent.Code, recent.Message)
}
for _, order := range recent.Value {
	fmt.Println(order.Sku)
}
```

`bijection.Query` runs a query once. `bijection.Mutate` runs a mutation as one
transaction:

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
placed := bijection.Mutate(ctx, client, ordersclient.App.Orders.Place,
	ordersclient.OrdersPlaceArgs{Sku: "A-1", Quantity: 2},
	bijection.Once(orderID))
```

`bijection.Once` names the one logical mutation. The same `once` and arguments
answer the original result, and the same `once` with other arguments refuses
`Invalid`. Without it the client mints one for the call.

A mutation whose reply was lost answers `Unknown`: it may have committed. Ask
again with the same `once`:
An uncertain mutation carries its original request key in `Result.Once`.

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
for attempt := 0; placed.Code == bijection.Unknown && attempt < 3; attempt++ {
	placed = bijection.Mutate(ctx, client, ordersclient.App.Orders.Place, args, bijection.Once(orderID))
}
```

## Frames

`As`, `Under`, `In` and `At` return a client in that frame. The original client
is unchanged.

| Method | Takes |
| - | - |
| `client.As(principal)` | A principal's id. Only an operator credential may act as another principal. |
| `client.Under(label)` | `bijection.Tag("access.finance")`, `bijection.Member("access.tenant", "acme")`, `a.And(b)` or `bijection.AnyOf(a, b)`. |
| `client.In(world)` | `bijection.Branch(name)` or `bijection.Version(version)`. |
| `client.At(instant)` | A `time.Time`: the valid instant. |

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
planning := client.In(bijection.Branch("plan-2027")).Under(bijection.Member("access.tenant", "acme"))
```

A committed mutation's result carries its `Version`. Pass it as
`bijection.Seen` to read your own write:

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
placed := bijection.Mutate(ctx, client, ordersclient.App.Orders.Place, args)
recent := bijection.Query(ctx, client, ordersclient.App.Orders.Recent, recentArgs, bijection.Seen(placed.Version))
```

The answer is then from state at least as new as that version.

## Results

Every verb answers a `bijection.Result[V]`:

| Field | Meaning |
| - | - |
| `OK` | Whether the call ended with a value. |
| `Value` | The value, typed by the ref. |
| `Version` | On a committed mutation: its commit version. |
| `Code` | A host code (`bijection.Unknown`, `Disallowed`, `Forbidden`, `Invalid`, `Absent`, `Exists`, `Conflict`, `Erased`, `Expired`, `Withdrawn`, `Limit`, `Failed`) or one of the function's declared codes. |
| `Reason` | On a host code: its precise cause (`BudgetExhausted` under `Limit`), or empty. |
| `Message` | The sentence the caller may read; it never starts with the code or the reason. |
| `Guard` | On `Forbidden`: the path of the guard that refused. |

A function's declared codes (its `refuses`) arrive as the function refused
them. Any other code the host answers is folded into its host code, and the
message keeps the original code.

## Watch

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
watch := bijection.Watch(ctx, client, ordersclient.App.Orders.Recent, args)
defer watch.Stop()
for result := range watch.Results() {
	if result.OK {
		render(result.Value)
	}
}
```

A watch delivers a `Result` each time the query's value changes, over one live
connection per frame. It reconnects on its own. `Stop`, or cancelling `ctx`,
ends it. A watch from a client with `In` or `At` reads once and then ends.

## Trial

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
trial := bijection.Trial(ctx, client, ordersclient.App.Orders.Place, args)
fmt.Println(trial.Result.OK, len(trial.Writes), len(trial.Tasks))
```

`bijection.Trial` runs the call in a discarded world and commits nothing. It
answers how the call would have ended (`trial.Result`, with `Guard` when a
guard refused), the writes it would have made (`Verb`, `Table`, `Key`,
`Before`, `After`) and the tasks it would have submitted (`Target`, `Args`,
`Due`). `ValidUntil` is the instant the answer is valid until (a call at the same
version committed before it is decided the same way), or nil when nothing
time-dependent bounds it.

## Values

| Bijection type | Go type |
| - | - |
| `t.string`, `t.key(table)` | `string` |
| `t.number` | `float64` |
| `t.int` | `int64` |
| `t.boolean` | `bool` |
| `t.bytes` | `[]byte` |
| `Decimal` | `bijection.Decimal` |
| `t.date` | `bijection.Date` |
| `t.instant` | `time.Time` |
| `t.duration` | `time.Duration` |
| `t.array(x)` | `[]X` |
| `t.map(x)` | `map[string]X` |
| an object | a generated struct |
| `t.maybe(x)`, an optional field | a pointer, or a nil slice or map |
| `t.one("a", "b")` | a generated string type with one constant per value |
| any other union | `any` |

A duration with years or months has no fixed length and does not fit
`time.Duration`: decoding one fails.

## Change entries

A query that returns a selection's changes answers `bijection.Change[T]`
entries:

```go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
type Change[T any] struct {
	Key     any
	Before  *T     // nil on an insert
	After   *T     // nil on a delete
	Version string // the change's version
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.