# Go

Source: https://tiltas.openpanel.sh/docs/sdks/go

> tiltas.openpanel.sh/go puts one Go program on your Network, with net.Listener, Dial, an HTTP client and WhoIs.

The Go package is a thin layer over Tailscale's `tsnet`, built against the same `tailscale.com` version as the Tiltas
engine. It adds what Tiltas needs: joining with a Join key, the Device's registration with the Panel, Service and
Device names, and leaving the Network on `Close`.

## Install

```sh
go get tiltas.openpanel.sh/go
```

Go 1.27.4 or newer; the go command fetches it when your `go.mod` asks for it. No cgo, no root and no TUN device: the
network runs in your process.

<Component type="warn" title="Beta: not published yet">
`tiltas.openpanel.sh/go` answers `go get` once the SDK's public repository exists. Until then, build against a copy
of the Tiltas repository with a `replace` line in your `go.mod`, as its examples do:

```sh
go mod edit -require=tiltas.openpanel.sh/go@v0.1.0 -replace=tiltas.openpanel.sh/go=../tiltas/sdk/go
go mod tidy
```
</Component>

## Use

```go
import "tiltas.openpanel.sh/go"

srv := &tiltas.Server{Name: "billing-api"} // the Join key comes from TILTAS_JOIN_KEY
defer srv.Close()
if err := srv.Up(ctx); err != nil {
	return err
}

ln, err := srv.Listen("tcp", ":80") // only on the Network
// …
res, err := srv.HTTPClient().Get("http://ledger/") // the Service named ledger
```

The complete server and client are in the [quickstart](/docs/sdks/quickstart).

## API

### type Server

```go
type Server struct {
	Name        string                               // Device name; default $TILTAS_NAME, else the host name
	Panel       string                               // default $TILTAS_PANEL, else https://tiltas.openpanel.sh
	JoinKeyFile string                               // default $TILTAS_JOIN_KEY, else $TILTAS_JOIN_KEY_FILE
	Persistent  bool                                 // keep the Device across restarts (needs Dir)
	Dir         string                               // state of a Persistent Server, mode 0700
	Logf        func(format string, args ...any)     // the network engine's verbose logs, secrets removed
	AppVersion  string                               // reported to the Panel; default tiltas-go/<version>
	Getenv      func(key string) string              // how TILTAS_* are read; default os.Getenv
}
```

Set the fields, then call `Up`. They must not change afterwards.

| Method | What it does |
|---|---|
| `Up(ctx) error` | Joins the Network on the first start, connects, and returns once this program is a Device with its own address. Give `ctx` a deadline: it waits as long as `ctx` allows. |
| `Close() error` | Disconnects. An ephemeral Server's Device leaves the Network. Safe to call twice. |
| `Listen(network, addr string) (net.Listener, error)` | Listens on the Network only. `network` is `tcp`, `tcp4`, `tcp6`, `udp`, `udp4` or `udp6`; `addr` is `":80"`. |
| `Dial(ctx, network, addr string) (net.Conn, error)` | Connects over the Network to `name:port`, where the name is a Device or a Service, short (`ledger`) or full (`ledger.<domain>`), or an address of the Network. Names are looked up in the Network's own DNS; a name it does not know is an error, never a query to the computer's DNS. |
| `HTTPClient() *http.Client` | An HTTP client that dials with `Dial`, so `http://ledger/` reaches the Service `ledger`. It ignores `HTTP_PROXY`. |
| `WhoIs(ctx, remoteAddr string) (*Identity, error)` | Who is behind the address of a connection that came in over the Network, such as `r.RemoteAddr`. |
| `DeviceID() string` | This Device's id in the console (`dev_…`). |
| `Domain() string` | The Network's domain; every name also answers as `<name>.<domain>`. |
| `IPs() (ip4, ip6 netip.Addr)` | This Device's addresses on the Network. |

### type Identity

```go
type Identity struct {
	DeviceID    string       // "dev_…" for Servers; empty for Personal devices
	Name        string       // the Device name, as in the console
	DNSName     string       // the Device's full name in the Network
	Kind        string       // "server" or "personal"
	Addresses   []netip.Addr // the Device's addresses on the Network
	Tags        []string
	MemberEmail string // the Member who owns a Personal device
	MemberName  string
}
```

### Errors

| Error | When |
|---|---|
| `ErrNoJoinKey` | Neither `TILTAS_JOIN_KEY`, `TILTAS_JOIN_KEY_FILE` nor `JoinKeyFile` gives a key. |
| `*PanelError` | The Panel refused: `Code` is `invalid_join_key` for an unknown, expired, revoked or used key, or the Network's Device allowance is full. |
| `ErrNotUp`, `ErrClosed` | A method that needs a running Server was called before `Up` or after `Close`. |

## Ephemeral or persistent

By default a Server is ephemeral: its keys live only in memory, a new Device joins on every start, and `Close` takes
it out of the Network. That suits containers, jobs and anything you scale out.

A persistent Server keeps its Device across restarts, like an installed app:

```go
srv := &tiltas.Server{Name: "nas-backup", Persistent: true, Dir: "/var/lib/nas-backup/tiltas"}
```

The first start joins with the Join key; later starts reuse the Device stored in `Dir` and need no key. `Dir` holds the
Device's keys: it is created with mode 0700, and must not be shared between two programs. Remove the Device in the
console to take it out of the Network.

## Examples

`examples/go` in the repository has the quickstart's `hello-server` and `hello-client`. They are run against a
development Network on every change, with clients in each language calling servers in each language.

## Build tags

The packages you build pull in `tailscale.com` from the Go module proxy. To leave out the parts that talk to
Tailscale's own servers, build with the Tiltas engine's tags:

```sh
go build -tags ts_omit_logtail,ts_omit_netlog,ts_omit_clientupdate,ts_omit_captiveportal,ts_omit_oauthkey,ts_omit_identityfederation,ts_omit_webclient,ts_omit_flashappliance,ts_omit_ace .
```

The SDK switches off log upload at run time either way. See [limitations](/docs/sdks/limitations) for the one
difference left.
