Go SDK Reference Go

Embed an nfltr tunnel agent directly in your Go application — no separate binary, no shell exec, no child process management.


Overview

The Go SDK is the agent code the nfltr CLI runs on, as a Go API. Your application calls agent.New(), Connect(ctx), and the tunnel is up; it runs in goroutines inside your process. Like the CLI, the agent makes one outgoing TLS connection to the relay (TCP by default, gRPC as a fallback) and reconnects by itself after network interruptions.

Install

go get github.com/nfltr/relay/client@latest

Basic usage

import "github.com/nfltr/relay/client/agent"

a := agent.New(agent.Config{
    ServerAddr: "grpc.nfltr.xyz:443",
    AgentID:      "my-service-01",
    TLSConfig:  machineTLS, // this machine's certificate: Authentication below
    Routes: []agent.Route{
        {Backend: "http://localhost:8080"}, // default
    },
})

if err := a.Connect(ctx); err != nil {
    log.Fatal(err)
}
log.Println("tunnel active, agent-id:", a.AgentID())

// Block until the context is cancelled or Close() is called.
<-a.Done()

Config

All parameters for the agent connection. Zero values are safe; ServerAddr, AgentID and a credential (TLSConfig with the machine certificate, or Token / TokenFile) are required.

ServerAddrstring required
Relay address with port. For nfltr.xyz pass "grpc.nfltr.xyz:443". Always set it: the built-in default is not a hosted address.
AgentIDstring required
Agent identifier (unique per hosted account). Must be unique on the relay. This is the name that appears in the /browse/<agent_id>/ URL path.
TLSConfig*tls.Config required (or Token)
Carries this machine's certificate: the agent authenticates as that machine. It also turns TLS on.
Token, TokenFilestring optional
Instead of a machine certificate: a token an identity provider of the relay authenticates (an OIDC token). TokenFile is read again at every connection, so another process may rewrite it before the token expires; the agent never refreshes a token itself.
TLSbool optional
Enable one-way TLS for the relay connection. Defaults to false. Set it to true with Token on a TLS port (e.g. 443). Ignored when TLSConfig is provided.
Routes[]Route optional
Backend routing table. The first entry without a Prefix acts as the default/fallback route. See Route below.
RequestTimeoutint optional
Per-request proxy timeout in seconds. Defaults to 60.
Logger*slog.Logger optional
Structured logger. Defaults to slog.Default().

Route

Describes a single backend target for incoming HTTP requests.

Backendstring required
Target URL for this route, e.g. "http://localhost:8080".
Prefixstring optional
URL path prefix (without leading slash) that activates this route. Empty prefix means default/fallback. The prefix is stripped before forwarding.

Examples

// Single backend (default)
Routes: []agent.Route{
    {Backend: "http://localhost:8080"},
}

// Multi-backend: /api → :8080, /ws → :4000, default → :3000
Routes: []agent.Route{
    {Prefix: "api", Backend: "http://localhost:8080"},
    {Prefix: "ws",  Backend: "http://localhost:4000"},
    {Backend: "http://localhost:3000"}, // fallback
}

Agent interface

The value returned by agent.New() implements this interface:

type Agent interface {
    // Connect dials the relay and starts the tunnel in the background.
    // It blocks until the first connection is established (or all retries
    // fail), then returns. A failed Connect closes Done. Call it once.
    Connect(ctx context.Context) error

    // AgentID returns the agent identifier.
    AgentID() string

    // Done returns a channel closed when the agent stops running.
    Done() <-chan struct{}

    // Connected reports whether the agent holds a connection the relay accepted.
    Connected() bool

    // Err is why the agent stopped once Done is closed: nil when its
    // context ended or Close was called, else the error that ended it.
    Err() error

    // Close stops the agent and waits for the tunnel to drain. Safe to call twice.
    Close()

    // RotateE2EECert makes a new self-signed certificate for TLS that ends
    // on this machine and returns its SHA-256 fingerprint.
    RotateE2EECert() (string, error)

    // RotateE2EECertFromFiles loads a new such certificate from PEM files.
    RotateE2EECertFromFiles(certFile, keyFile string) (string, error)

    // Stats returns the agent's counters, for a metrics collector.
    Stats() Stats

    // SetLabels replaces the labels the agent advertises beyond WithLabels'.
    SetLabels(labels map[string]string) error
}

Options

WithLabels

Attach key-value metadata to the agent connection. The relay carries the labels as given: they appear in presence and agent listings, which can filter by label:

a := agent.New(cfg, agent.WithLabels(map[string]string{
    "env":     "production",
    "region":  "us-east",
    "version": "v2.1.0",
}))

Complete example

package main

import (
    "context"
    "crypto/tls"
    "encoding/json"
    "log"
    "os"
    "os/signal"
    "path/filepath"
    "syscall"

    "github.com/nfltr/relay/client/agent"
)

// machineCert reads the certificate nfltr login saved for this machine
// (~/.config/nfltr/machine.json, its chain field) and its key (machine.key).
func machineCert() (*tls.Certificate, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return nil, err
    }
    dir := filepath.Join(home, ".config", "nfltr")
    js, err := os.ReadFile(filepath.Join(dir, "machine.json"))
    if err != nil {
        return nil, err
    }
    var saved struct {
        Chain string `json:"chain"`
    }
    if err := json.Unmarshal(js, &saved); err != nil {
        return nil, err
    }
    key, err := os.ReadFile(filepath.Join(dir, "machine.key"))
    if err != nil {
        return nil, err
    }
    cert, err := tls.X509KeyPair([]byte(saved.Chain), key)
    if err != nil {
        return nil, err
    }
    return &cert, nil
}

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()

    // Read the pair again at every connection: the CLI renews the
    // 24-hour certificate in place.
    machineTLS := &tls.Config{
        GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
            return machineCert()
        },
    }

    a := agent.New(
        agent.Config{
            ServerAddr: "grpc.nfltr.xyz:443",
            AgentID:    "payment-service",
            TLSConfig:  machineTLS,
            Routes: []agent.Route{
                {Prefix: "api", Backend: "http://localhost:8080"},
                {Prefix: "health", Backend: "http://localhost:8081"},
                {Backend: "http://localhost:8080"},
            },
        },
        agent.WithLabels(map[string]string{"env": "prod"}),
    )

    if err := a.Connect(ctx); err != nil {
        log.Fatalf("connect: %v", err)
    }
    log.Printf("tunnel active: https://nfltr.xyz/browse/%s/", a.AgentID())

    <-ctx.Done()
    a.Close()
    <-a.Done()
    log.Println("shutdown complete")
}

Authentication

The relay authenticates an agent by its machine certificate (or, for a workload, by an OIDC token: Token / TokenFile). Enrol the machine once with nfltr login (headless: nfltr login --code-file - with a code from the dashboard's Add machines); its key is made on the machine and never leaves it. The certificate is saved beside the config as machine.json (the chain in its chain field) and machine.key; the machineCert function of the complete example loads the pair:

machineTLS := &tls.Config{
    GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
        return machineCert() // read again at every connection
    },
}

The certificate lasts 24 hours and the CLI renews it in place, so reading the pair at every connection (as above) keeps a long-running program on the current certificate.


Error handling

Connect returns an error if the initial dial fails. Once connected, the agent reconnects automatically on transient failures. Monitor the Done() channel for permanent shutdown:

if err := a.Connect(ctx); err != nil {
    // Fatal: bad credentials, server unreachable, etc.
    log.Fatalf("connect: %v", err)
}

// Agent is now running. Done() closes when:
//   - ctx is cancelled
//   - Close() is called
//   - A non-recoverable error occurs (Err says which)
go func() {
    <-a.Done()
    log.Println("agent disconnected")
}()

Use cases


Kubernetes operator

The Go SDK can be embedded in a Kubernetes controller. In this sketch each AgentTunnel custom resource (a type of your own) maps to one agent.Agent instance started by the controller's reconcile loop.

// In your controller's Reconcile() method:
func (r *AgentTunnelReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
    // ... fetch the AgentTunnel CR ...

    a := agent.New(agent.Config{
        ServerAddr: cr.Spec.ServerAddr,
        AgentID:      cr.Spec.AgentID,
        TLSConfig:  machineTLS, // the certificate of the machine this controller runs as
        Routes:     routesFromSpec(cr.Spec.Routes),
    })
    if err := a.Connect(ctx); err != nil {
        return ctrl.Result{}, err
    }
    r.agents.Store(req.NamespacedName, a)
    return ctrl.Result{}, nil
}