Skip to content

Go

The Go function SDK lets you write a function as ordinary net/http handlers. You register them in init(), build the program to WebAssembly (GOOS=wasip1), and the function runner loads the module. The package is fn, has no third-party dependencies and needs Go 1.24 or later.

Functions are first-party code, run in a sandbox that provides fault isolation rather than a defence against a hostile author (decision). The same contract is implemented by the TypeScript, Rust and Java SDKs; what stays stable across versions is set out in function stability.

The SDK is a Go module inside the platform repository, served by the Go module proxy from tags of the form clients/fn-go/vX.Y.Z. The current release is v0.5.0.

Terminal window
go get github.com/flowcatalyst/flowcatalyst/clients/fn-go@v0.5.0

fcdev fn init writes a project with this dependency in place; see Develop locally with fcdev fn dev. The module path in code is github.com/flowcatalyst/flowcatalyst/clients/fn-go; it is imported under the name fn.

A function is a main package with an empty main and init() registrations. Registration never touches the host: the SDK builds the describe document from what init() declared.

package main
import (
"net/http"
fn "github.com/flowcatalyst/flowcatalyst/clients/fn-go"
)
var greeting = fn.Config("GREETING")
func init() {
fn.Open("GET /healthz", health)
fn.Platform("GET /hello/{name}", hello)
}
func main() {}
func health(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }
func hello(w http.ResponseWriter, r *http.Request) {
g, found, _ := greeting.Get(r.Context())
if !found {
g = "Hello"
}
_, _ = w.Write([]byte(g + ", " + r.PathValue("name")))
}

Requests are routed through a standard http.ServeMux, so patterns are "METHOD /path/{param}" and r.PathValue reads parameters. A handler that panics is turned into 500 {"error":"FUNCTION_PANIC"}.

Terminal window
GOOS=wasip1 GOARCH=wasm go build -buildmode=c-shared -o hello.wasm ./examples/hello

The module exports fc_abi_v1, fc_alloc, fc_handle and fc_describe (Guest ABI v1; see the ABI reference). A Go module is large: the repository’s hello example is about 7.6 MB unstripped and 7.5 MB with -ldflags="-s -w". The Rust SDK produces modules a fiftieth of that size if size matters to you. wasm-opt -Os did not validate a Go 1.27 module when last tried.

All declarations belong in init().

Function Declares
fn.Webhook(pattern, h, opts...) A webhook endpoint: the runner verifies the platform’s delivery signature. POST only; any other method panics
fn.Platform(pattern, h, opts...) An endpoint that needs a verified platform access token
fn.Open(pattern, h, opts...) An endpoint with no authentication; the function authenticates for itself
fn.Subscribe(eventType, path, opts...) Deliveries of an event type go to the webhook endpoint at path
fn.Schedule(cron, path, opts...) A cron firing at the webhook endpoint at path
fn.Config(key), fn.Secret(key), fn.DB(name) A config key, secret key or database binding
fn.HTTPAllow(hosts...) Hosts outbound HTTP may reach (api.example.com, or *.example.com)
fn.Emits(eventTypes...) Event types the function may emit
fn.Dispatches(target, path, opts...) A function and webhook path the function may create dispatch jobs for
fn.UsesPlatformToken() Permission to fetch a platform access token
fn.TraceContexts(contexts...) Named trace contexts

Endpoint options: fn.Timeout(d), fn.MaxBody(n) and fn.CORS(fn.CORSConfig{Origins, Methods, Headers, AllowCredentials}). Subscription options: fn.Mode("IMMEDIATE"), fn.MaxRetries(n), fn.DataOnly() and fn.SubTimeout(d). Schedule options: fn.Timezone("Africa/Johannesburg") and fn.Payload(json.RawMessage). Schedule cron is six-field with seconds first ("0 */5 * * * *"); publishing rejects a five-field expression (see cron).

A subscription or schedule must point at a webhook endpoint the function also declares. The platform checks the full document at publish; see Declare endpoints, auth, subscriptions and schedules.

Call Returns
r.PathValue(name), r.URL.Query(), r.Header, r.Body The standard net/http request
fn.CallerFrom(ctx) A Caller: Kind() ("webhook", "principal" or "anonymous") and Principal() (nil unless the caller is a platform principal)
fn.Invocation(ctx) An Info with ID, Address, Version and Deadline

Principal has the fields ID, Type, Tier, Clients, ClientCodes, Roles, Applications, AllApplications and Permissions, and the methods IsAnchor, HasRole, CanAccessClient, CanAccessClientCode, CanAccessApplication, CanAccessApplicationCode and HasPermission. HasPermission uses the platform’s wildcard matching (see permissions).

Return a normal net/http response. Two helpers express the delivery outcomes (delivery):

Call Response A delivery treats it as
any 2xx as written delivered
fn.Retry(w, d) 429 with Retry-After (at least 1 s) try again later without spending an attempt
fn.Reject(w, reason) 422 with FlowCatalyst-Outcome: reject; reason is the plain-text body give up now

Anything else, a crash or a timeout is a failed attempt, retried up to the subscription’s limit.

Each capability works only for what the function declared; an undeclared use fails with NOT_DECLARED.

value, found, err := greeting.Get(ctx) // *fn.ConfigValue
token, found, err := apiToken.Get(ctx) // *fn.SecretValue, from fn.Secret("API_TOKEN")

Values are set on the platform per function (Give a function secrets and config). Promotion is refused while a declared key has no value.

fn.HTTPClient() returns an *http.Client whose transport runs through the host. Only hosts in fn.HTTPAllow are reachable, including on redirects, and the request context’s deadline becomes the call timeout.

req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.example.com/ping", nil)
resp, err := fn.HTTPClient().Do(req)
id, err := fn.Emit(ctx, fn.Event{
Type: "hello:greeting:greeting:sent",
DedupID: "greeting-sent-" + inbound.ID, // derive from what you are handling
Source: "hello.example",
ContentType: "application/json",
Data: []byte(`{"ok":true}`),
})

Only declared types of your own application can be emitted. Event also carries Subject, CorrelationID, CausationID and MessageGroup. Always derive DedupID from the input so a redelivery emits once.

fn.Dispatches("hello.logger", "/deliver",
fn.DispatchConnection("hello-conn"), // required: Dispatches panics without it
fn.DispatchPool("hello-pool")) // optional
jobID, err := fn.Dispatch(ctx, fn.Job{
Target: "hello.logger",
Path: "/deliver",
Payload: []byte(`{"hello":"world"}`),
Metadata: map[string]string{"from": "hello"},
MessageGroup: "hello",
})

The connection and pool are the declaration’s and cannot be overridden per call; the platform resolves them on every call, and the connection’s service account signs the delivery. Dispatch is not de-duplicated: retrying after an ambiguous failure can create a second job. Job also has Code, Subject, MetadataEntries, Mode, CorrelationID, CausationID, ContentType, Descriptor, MaxRetries, TimeoutSeconds and DataOnly. See Create a dispatch job from a function and dispatch jobs.

fn.DB("main").SQL() returns a *sql.DB backed by a driver named fc that runs over the host. Use ? placeholders. []byte parameters are sent base64-encoded and time.Time as RFC 3339 with nanoseconds. A JSON or JSONB column arrives as a string you can json.Unmarshal. Results are capped at 10 000 rows or 8 MiB, and a transaction still open when the call ends is rolled back.

var main = fn.DB("main")
rows, err := main.SQL().QueryContext(ctx, "SELECT id, name FROM people WHERE id = ?", id)
func init() { fn.UsesPlatformToken(); fn.HTTPAllow("other-app.example.com") }
token, err := fn.PlatformToken(ctx) // cached by the host
token, err = fn.PlatformToken(ctx, fn.Refresh()) // after a 401 from the target

The token is the access token of the service account linked to the function’s application. Call it per request, send it as a bearer, and never log it. See Call another service with a platform token.

fn.Log(ctx) returns a *slog.Logger over the host’s log op. Trace logs are gated by operators and are a no-op until a context is switched on (Switch on trace logs):

func init() { fn.TraceContexts(fn.TraceContext{Name: "orders", Description: "What the mapping decided"}) }
fn.SetReference(ctx, orderNo)
if fn.Tracing(ctx, "orders") {
fn.Trace(ctx, "orders", "mapped", map[string]any{"lines": 3}, fn.WithLevel(fn.TraceDebug))
}

Levels are TraceDebug, TraceInfo, TraceWarn and TraceError; fn.WithReference(ref) stamps one record. A context name is lowercase, at most 40 characters, and http is reserved; a description is at most 200 bytes. None of the trace calls can fail the invocation.

Host failures are *fn.Error with a Code such as NOT_DECLARED, NOT_ALLOWED, DEADLINE, TOO_LARGE, UNAVAILABLE, BAD_REQUEST, DB_CONSTRAINT, DB_SYNTAX, DB_TIMEOUT, DB_UNAVAILABLE, DB_ERROR or UNKNOWN_OP. Test retryability with errors.Is(err, fn.ErrRetryable), which is true only for UNAVAILABLE (platform trouble). Every other code is final, so reject rather than retry:

if err != nil {
if errors.Is(err, fn.ErrRetryable) {
fn.Retry(w, 5*time.Second)
return
}
fn.Reject(w, "emit refused")
return
}

On a host OS (not wasip1) the package runs against a fake host, so a plain go test exercises real handlers in milliseconds.

func TestHello(t *testing.T) {
defer fn.SetHost(&fn.FakeHost{Handler: func(op int32, meta, body []byte) ([]byte, []byte, *fn.Error, error) {
return nil, nil, nil, nil // script per-op results here
}})()
resp := fn.InvokeForTest(fn.TestRequest{
Method: "GET", Path: "/hello/Aroha",
Principal: &fn.Principal{ID: "prn_1"},
})
if resp.Status != 200 {
t.Fatalf("status %d", resp.Status)
}
}

InvokeForTest builds a real request frame, routes it through your init() registrations and reads the response back. TestRequest has Method, Path, Query, Header, Body, Principal (a platform caller) and Webhook (a signature-verified delivery); neither set means an anonymous caller. DescribeForTest() returns the describe JSON. FakeHost.Calls records every host call for assertions. These helpers are compiled out of wasip1 builds.

To run your function against the real runner with no platform, use fcdev fn dev; to check signing, connections and real delivery, fcdev fn deploy to a non-production platform (Publish, promote and use aliases).

Defaults per function: 64 MB memory, 16 concurrent calls, 30 s timeout and a 1 MiB request body, all settable (timeout and body also per endpoint). A call past its concurrency limit is answered 429 and deliveries wait without spending an attempt. Outbound HTTP responses over 16 MiB are refused. See Functions for the full list.