Skip to main content

Go SDK

note

This is a platform SDK — it covers the full Kilimanjaro API surface: data, auth (Gate), migrations, functions, policies, audit, org management, and realtime subscriptions. A separate mobile SDK family handles auth-only mobile use cases.

The Go SDK surfaces every Kilimanjaro API operation in idiomatic Go: exported PascalCase identifiers, context.Context as the first argument to every call, and tuple-return (data, meta, *KError) in place of exceptions. The vanity import path k9o.dev/sdk-go resolves via a go-import meta page; the source mirror lives at github.com/k9o-dev/sdk-go.

Runtime baseline. Go 1.22 or later. The SDK has no CGo dependencies and compiles to a static binary on all platforms Go 1.22 targets.


Installation​

go get k9o.dev/sdk-go

Module coordinate: k9o.dev/sdk-go. Import as:

import k9o "k9o.dev/sdk-go"

Setup​

Construct the client with k9o.NewClient and a k9o.ClientOpts literal. Supply your OrgSlug, ProjectSlug, and APIKey. BaseURL is optional — it defaults to https://api.k9o.io, and when you also supply OrgSlug the SDK derives the canonical https://<orgSlug>.api.k9o.io for you. The snippet below passes BaseURL explicitly for clarity; you may omit it. Self-hosted and Sovereign deployments pass their own host. A path-bearing URL causes NewClient to return K9O_INVALID_BASE_URL at construction time, before any network call is made.

Go
package main

import (
	"log"
	"os"

	k9o "k9o.dev/sdk-go"
)

func main() {
	client, kerr := k9o.NewClient(k9o.ClientOpts{
		BaseURL:     "https://acme.api.k9o.io", // optional
		OrgSlug:     "acme",
		ProjectSlug: "member-portal",
		APIKey:      os.Getenv("K9O_API_KEY"),
	})
	if kerr != nil {
		log.Fatalf("[%s] %s", kerr.Code, kerr.Message)
	}
	_ = client
}

Showing example in Go

Never hard-code the API key. Read it from an environment variable — for example K9O_API_KEY — or a secrets manager. The key must not appear in source control.

Self-hosted or Sovereign override​

For a self-hosted cluster or a Sovereign Control / Private Perimeter deployment, supply BaseURL with your own host — scheme and host only, no path:

Go
client, kerr := k9o.NewClient(k9o.ClientOpts{
	OrgSlug:     "acme",
	ProjectSlug: "member-portal",
	APIKey:      os.Getenv("K9O_API_KEY"),
	BaseURL:     "https://platform.acme.internal", // scheme + host only
})

Showing example in Go

Supplying a path-bearing URL (for example https://api.k9o.io/v2) causes NewClient to return K9O_INVALID_BASE_URL at construction time, before any network call is made. For local development use http://localhost:8080.


Getting started​

The first operation most applications make is querying a data collection — build a query, execute it, and handle *KError. Signing users in has its own section below.

Go
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	k9o "k9o.dev/sdk-go"
)

func main() {
	client, kerr := k9o.NewClient(k9o.ClientOpts{
		BaseURL:     "https://acme.api.k9o.io", // optional
		OrgSlug:     "acme",
		ProjectSlug: "member-portal",
		APIKey:      os.Getenv("K9O_API_KEY"),
	})
	if kerr != nil {
		log.Fatalf("[%s] %s", kerr.Code, kerr.Message)
	}

	ctx := context.Background()

	// Query a collection using the free generic helper (Go has no method type-params).
	// SelectExecute[T] is a package-level function, not a method on the client.
	rows, meta, kerr := k9o.SelectExecute[map[string]any](ctx,
		client.From("posts").Select().Eq("status", "published").Limit(10))
	if kerr != nil {
		log.Fatalf("[%s] %s", kerr.Code, kerr.Message)
	}
	for _, row := range rows {
		fmt.Println(row)
	}
	if meta.Cursor != nil && meta.Cursor.Next != nil {
		fmt.Println("next cursor:", *meta.Cursor.Next)
	}
}
Output · bash
map[id:post_1 status:published title:Hello]
map[id:post_2 status:published title:World]
next cursor: <opaque cursor>  (printed only when another page exists)

Showing example in Go

note

SelectExecute[T] is a free generic function (k9o.SelectExecute[T](ctx, builder)), not a method on the client — Go does not support type parameters on methods.

meta.Cursor can be nil, and meta.Cursor.Next is a *string that is nil on the final page.

Collection rows are returned as []map[string]any. Kilimanjaro collections are customer-defined at runtime, so the SDK uses Go's built-in open-map type rather than pre-generated structs. Fixed control-plane shapes — errors, pagination, auth responses — are fully typed.


Authenticating your End-Users​

This server SDK covers password sign-in and session management: SignIn, SignUp, SignOut, WhoAmI, and RefreshToken. Social-IdP (OAuth2 redirect) and passwordless flows (magic-link and OTP) are browser/mobile flows that rely on window.location and are not available on server SDKs — see the TypeScript SDK and mobile SDK pages, or the Auth API reference for those flows and the full Gate surface. RevokeAllSessions ends every session of the signed-in user, this device included; access tokens already issued live until they expire. See Session lifetime and sign-out.

Password
ctx := context.Background()

session, kerr := client.Gate.SignIn(ctx, k9o.SignInInput{Email: "[email protected]", Password: "…"})
if kerr != nil {
	log.Printf("[%s] %s", kerr.Code, kerr.Message)
	return
}
fmt.Println("signed in:", session.Data)
Output · bash
signed in: map[session:map[accessToken:eyJhbGciOiJSUzI1NiIs... expiresAt:2026-10-27T10:15:00Z refreshToken:...] user:map[email:[email protected] id:eu_8f3kQ2mZ roles:[PROJECT_END_USER] status:active]]

Showing example in Password


Handling errors​

The Go SDK uses tuple-return. Calls return (data, meta, *KError) or (data, *KError), depending on whether the response carries meta. On success kerr is nil and data holds the result. On failure kerr is a non-nil *KError and data is the zero value.

KError exports four fields, all PascalCase per Go convention:

FieldTypeDescription
CodestringSCREAMING_SNAKE_CASE error code from the closed error catalogue
MessagestringHuman-readable description; safe to log and surface
Contextinterface{}Family-specific structured fields; shape varies per code family
RecommendationstringActionable hint; empty when no hint applies

Parse the root-level KError directly — the wire shape is { code, message, context, recommendation } with no wrapper object. Match on the full K9O_-prefixed code string.

Go
rows, meta, kerr := k9o.SelectExecute[map[string]any](ctx, client.From("posts").Select())
if kerr != nil {
	switch kerr.Code {
	case "K9O_TIER_CAP_HIT":
		// Project has hit a tier-bound cap (MAU, storage, etc.).
		fmt.Printf("tier cap hit: %s\n", kerr.Recommendation)
	case "K9O_COLLECTION_NOT_FOUND":
		fmt.Printf("collection not found: %s\n", kerr.Message)
	case "K9O_ACCESS_DENIED":
		fmt.Printf("access denied: %v\n", kerr.Context)
	default:
		fmt.Printf("[%s] %s\n", kerr.Code, kerr.Message)
	}
	// Output (illustrative; on failure):
	// [<code>] <message>  (or the tier cap, collection or access-denied line for those codes)
	return
}
_, _ = rows, meta

Showing example in Go

Common codes you will encounter:

CodeHTTPWhen it fires
K9O_INVALID_CREDENTIALS401Email or password mismatch on Gate sign-in
K9O_COLLECTION_NOT_FOUND404From(name) references a collection that does not exist in the project
K9O_ACCESS_DENIED403Caller lacks the authority required for the operation
K9O_TIER_CAP_HIT409Project has reached a tier-bound cap (MAU, storage GB, etc.)
K9O_TIER_RATE_LIMIT_EXCEEDED429Call rate exceeded for the current tier
K9O_INVALID_BASE_URL(SDK init)BaseURL supplied with a path segment or without a scheme

The full catalogue and per-code context shapes are at /api/conventions#23-universal-error-families.


Realtime subscriptions​

The Go SDK delivers realtime events over Server-Sent Events as a Go channel. Subscribe with client.Realtime.Subscribe and range over the events channel; failures arrive on the second channel. A stream lasts up to 300 seconds; to continue after it ends, reconnect with the last event id as Last-Event-ID and drop duplicates by eventId (the client contract, see the Realtime API reference). There is no initial-state replay: read the current rows first, then subscribe for changes.

Go
events, errs := client.Realtime.Subscribe(ctx, k9o.RealtimeTopic.Collection("posts"), k9o.SubscribeOptions{})
for event := range events {
	fmt.Printf("%s: %s\n", event.EventType, event.Payload)
}
if kerr := <-errs; kerr != nil {
	log.Printf("[%s] %s", kerr.Code, kerr.Message)
}
Output · bash
row_inserted: {"id":"order-124","total":42}
row_deleted: {"id":"order-124"}

Showing example in Go

Each event is { Topic, EventType, Payload, OccurredAt }. Cancel the ctx to unsubscribe cleanly.

For topics and the frame format, see the Realtime API reference.

Streams​

Streams are ordered and replayable. The minimum maxBytes is 10485760 (10 MiB), and the stream's Slug is what the other calls take. Sequence is a string. Subscribe delivers on a channel and reports a failure on a second one; read the error channel after the loop.

Go
stream, _, kerr := client.Streams.Create(ctx, "orders", 10_485_760, 0)
if kerr != nil {
	log.Fatalf("[%s] %s", kerr.Code, kerr.Message)
}
client.Streams.Publish(ctx, stream.Slug, map[string]any{"id": 1, "total": 42}, "eu.new")
client.Streams.Publish(ctx, stream.Slug, map[string]any{"id": 2, "total": 17}, "")

subCtx, cancel := context.WithCancel(ctx)
defer cancel()
events, errs := client.Streams.Subscribe(subCtx, stream.Slug, "") // "" starts at the beginning
for event := range events {
	fmt.Println(event.Sequence, string(event.Data)) // 1 {"id":1,"total":42}
	if event.Sequence == "2" {
		cancel()
	}
}
if kerr := <-errs; kerr != nil {
	log.Printf("[%s] %s", kerr.Code, kerr.Message)
}

from := int64(0)
page, _, _ := client.Streams.Replay(ctx, stream.Slug, k9o.ReplayOptions{FromSequence: &from, Limit: 10})
fmt.Println(len(page.Events), page.HasMore)
Output · bash
1 {"id":1,"total":42}
2 {"id":2,"total":17}
2 false

Showing example in Go


See also​

  • API reference — full REST reference for every surface
  • Conventions — response envelope, KError shape, URL grammar, versioning
  • CLI — k9o command-line interface
  • SDKs — all twelve supported languages