> Markdown version of https://tuna.am/en/docs/guides/install/sdk/go/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# Golang

The Go SDK opens Tuna tunnels straight from your code: expose a local HTTP or TCP service at a public address without installing `tuna`.

* Two ways in: `Listen` returns a `net.Listener` for your own server, `Forward` proxies connections to a local address.
* Survives network failures: reconnects and keeps the same public address.
* Dependencies are only the standard library and `golang.org/x/crypto/ssh`.

[tuna-tiny](https://tuna.am/en/docs/guides/install/install-tiny.md), a 2 MB client for routers and containers, is built on this SDK.

> **Info.** The API is not stable yet: it may change before v1.

API reference is on [pkg.go.dev](https://pkg.go.dev/github.com/yuccastream/tuna-sdk-go), source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-go).

## Installation

```shell
go get github.com/yuccastream/tuna-sdk-go

```

If proxy.golang.org is unavailable, the module is mirrored in the `code.tuna.am` package registry. Add it as a `GOPROXY`; other dependencies come from the usual sources:

```shell
GOPROXY=https://code.tuna.am/api/packages/tuna/go,https://proxy.golang.org,direct \
  go get github.com/yuccastream/tuna-sdk-go

```

If sum.golang.org is unavailable too, add `GONOSUMDB=github.com/yuccastream/tuna-sdk-go`: checksum database verification is turned off only for this module, and your project's `go.sum` pins the version. Don't use `GOSUMDB=off`: it turns off verification for all modules.

The package name is `tuna`. Requires Go 1.26 or later. To learn about new SDK versions, use `go list -m -u`, Dependabot or Renovate.

## Authentication

Create an [API key](https://my.tuna.am/api_keys?lang=en) with the `tunnels:connect` permission and pass it in `Options.APIKey` or the `TUNA_API_KEY` environment variable.

## Serve HTTP without a local port

`Listen` gives you the tunnel as a regular `net.Listener`: your server accepts connections from the internet, no local port needed.

```go
ln, err := tuna.Listen(ctx, tuna.Options{Protocol: "http"})
if err != nil {
	return err
}
defer ln.Close()

fmt.Println("public URL:", ln.URL())
return http.Serve(ln, handler)

```

`Close` works like on any `net.Listener`: `http.Server.Shutdown` lets in-flight requests finish before the tunnel disconnects.

## Forward to a local service

`Forward` proxies connections from the tunnel to a local address, `host:port` or `unix:///path/to.sock`. It blocks until `ctx` is cancelled or the tunnel ends for good.

```go
err := tuna.Forward(ctx, tuna.Options{
	Protocol: "tcp",
	Port:     "my-db",
	OnEvent: func(e tuna.Event) {
		if e.Type == tuna.EventConnected {
			log.Printf("forwarding %s -> 127.0.0.1:5432", e.URL)
		}
	},
}, "127.0.0.1:5432")

```

## Options

| `Options` field                        | Meaning                                                                                                                                                          |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Protocol`                             | `http` or `tcp`, required                                                                                                                                        |
| `APIKey`                               | API key, defaults to `$TUNA_API_KEY`                                                                                                                             |
| `Subdomain`, `Domain`                  | HTTP: [reserved subdomain](https://tuna.am/en/docs/tunnels/http.md#reserved-subdomain) or [custom domain](https://tuna.am/en/docs/tunnels/http.md#custom-domain) |
| `Port`                                 | TCP: [reserved port](https://tuna.am/en/docs/tunnels/ports.md) or its alias                                                                                      |
| `ProxyProtocol`                        | TCP: [PROXY protocol](https://tuna.am/en/docs/tunnels/tcp.md#proxy-protocol) version, `1` or `2`                                                                 |
| `CIDRAllow`, `CIDRDeny`                | TCP: client subnets allowed or rejected by the Tuna node                                                                                                         |
| `OnEvent`                              | callback for tunnel events                                                                                                                                       |
| `ConnectTimeout`                       | limit on the wait for the first connection; zero means no limit                                                                                                  |
| `ServerURL`, `TLSConfig`, `ClientName` | API address, TLS settings for it, client name reported to the server                                                                                             |

## Events and errors

`OnEvent` receives `connected`, `reconnecting`, `reconnected`, `banner`, `session_expiring`, `terminated` and `local_error`. Calls never overlap and run on the tunnel's goroutines, so keep the callback short. The SDK prints nothing itself: text messages from the server for the user arrive as a `banner` event.

Network failures and temporary server errors are retried: the pause grows from 1 to 15 seconds with random jitter, and `Retry-After` is respected. The tunnel ends with an error when retrying is pointless; check it with `IsPermanent`:

* `*ServerError`: the API rejected the request — bad or revoked key, missing permission, unknown reserved name, unpaid plan;
* `*TerminatedError`: the server closed the tunnel — it was deleted, suspended or hit the session time limit.

## Behavior worth knowing

* The context passed to `Listen` bounds the whole life of the tunnel, not only the first connection; cancelling it cuts off every accepted connection. To give up early when the tunnel does not come up, set `ConnectTimeout`.
* `Close` stops accepting and reconnecting, but the tunnel stays connected until the last accepted connection is closed. `http.Server.Shutdown` does not wait for or close hijacked connections such as WebSockets: they keep the tunnel open until your code closes them or the context is cancelled.
* When the visitor closes its side of a connection, the connection is closed in both directions: a response sent after that is lost.
* The `Host` header and the PROXY protocol header reach your service as sent.
* The API client is `net/http` and honors `HTTPS_PROXY`. Connections to Tuna nodes are plain SSH and do not use the proxy.
* Use `TLSConfig` for a private CA or for environments without system root certificates, such as `scratch` images.

## Protocol

The SDK implements the open [Tuna client protocol](https://tuna.am/en/docs/guides/client-protocol.md): `POST /v1/connect` followed by a standard SSH remote forward to the node. You can use the spec to write a client in another language.
