# SDK quickstart

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

> Serve a page only on your Network from one program, and call it by name from another.

You will run two small programs. `hello-server` answers HTTP on your Network only and greets each caller by the Device
name it calls from. The client calls it by the name of a Service, `hello`. Both join with a Join key and leave the Network when they stop.

## 1. Make a Join key

In the console, under **Join keys**, create a **reusable** key named after what it is for, such as `sdk quickstart`.
Copy it while it is on screen, and give it to both programs through the environment:

```sh
export TILTAS_JOIN_KEY=qlj_your_join_key
```

## 2. Install

**Go**

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

**Python**

```sh
pip install tiltas
```

**Node.js**

```sh
npm install tiltas
```

<Component type="warn" title="Beta">
Until the packages are on the registries, install from a build: see Install on the [Go](/docs/sdks/go#install),
[Python](/docs/sdks/python#install) or [Node.js](/docs/sdks/node#install) page.
</Component>

## 3. Serve on the Network

Save the server and start it as the Device `hello-server`:

**Go**

```go title="examples/go/hello-server/main.go"
// Command hello-server answers HTTP requests that come over a Tiltas
// Network, and only those: it opens no port on the computer it runs on.
//
//	TILTAS_JOIN_KEY=qlj_… TILTAS_NAME=hello-server go run ./hello-server
package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"tiltas.openpanel.sh/go"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	srv := &tiltas.Server{} // the name comes from TILTAS_NAME, the key from TILTAS_JOIN_KEY
	defer srv.Close()       // an ephemeral Device leaves the Network here

	upCtx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	if err := srv.Up(upCtx); err != nil {
		return err
	}
	ln, err := srv.Listen("tcp", ":80")
	if err != nil {
		return err
	}

	hs := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		who, err := srv.WhoIs(r.Context(), r.RemoteAddr)
		if err != nil {
			http.Error(w, "unknown caller", http.StatusForbidden)
			return
		}
		fmt.Fprintf(w, "hello %s\n", who.Name)
	})}
	go func() {
		<-ctx.Done()
		hs.Shutdown(context.Background())
	}()
	log.Printf("serving on the Network only, as Device %s", srv.DeviceID())
	if err := hs.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
		return err
	}
	return nil
}
```

```sh
TILTAS_NAME=hello-server go run ./hello-server
```

**Python**

```python title="examples/python/server.py"
"""Answers HTTP requests that come over a Tiltas Network, and only those.

    TILTAS_JOIN_KEY=qlj_… TILTAS_NAME=hello-server python server.py
"""

import http.server
import signal
import sys

import tiltas

class Hello(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            who = server.whois(self.client_address)
        except tiltas.TiltasError:
            self.send_error(403, "unknown caller")
            return
        body = f"hello {who.name}\n".encode()
        self.send_response(200)
        self.send_header("Content-Type", "text/plain; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

# Leave the Network on `docker stop` and `kill` too, not only on Ctrl-C.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))

with tiltas.Server() as server:  # the name comes from TILTAS_NAME, the key from TILTAS_JOIN_KEY
    httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Hello, bind_and_activate=False)
    httpd.socket.close()
    httpd.socket = server.listen(80)
    print(f"serving on the Network only, as Device {server.device_id}", flush=True)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
```

```sh
TILTAS_NAME=hello-server python server.py
```

**Node.js**

```js title="examples/node/server.mjs"
// Answers HTTP requests that come over a Tiltas Network, and only those.
//
//   TILTAS_JOIN_KEY=qlj_… TILTAS_NAME=hello-server node server.mjs
import { Server } from 'tiltas';

const tiltas = new Server(); // the name comes from TILTAS_NAME, the key from TILTAS_JOIN_KEY
await tiltas.up();

const http = await tiltas.listen(80, async (req, res) => {
  try {
    const who = await tiltas.whois(req);
    res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' }).end(`hello ${who.name}\n`);
  } catch {
    res.writeHead(403).end('unknown caller\n');
  }
});
console.log(`serving on the Network only, as Device ${tiltas.deviceId}`);

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, async () => {
    http.close();
    await tiltas.close(); // an ephemeral Device leaves the Network
    process.exit(0);
  });
}
```

```sh
TILTAS_NAME=hello-server node server.mjs
```

It prints `serving on the Network only, as Device dev_…`, and `hello-server` appears under Devices in the console, as
a Server. Nothing listens on the computer itself: port 80 exists only on the Network.

## 4. Let the client in

New Servers reach nothing and nobody reaches them. In the console, open **Services → New Service**:

- **Name** `hello`, **kind** Web, on the Device `hello-server`, target `localhost:80`;
- **Who can use it**: the Group your client will be in, or the client's Device once it exists.

A Join key with Groups puts every Device that joins with it into those Groups, which suits a client that starts many
times. See [Services](/docs/services) and [Access rules](/docs/access).

## 5. Call it by name

Run the client with a Join key of the Group you allowed, as `client`:

**Go**

```go title="examples/go/hello-client/main.go"
// Command hello-client calls a Service by name over a Tiltas Network and
// prints the answer.
//
//	TILTAS_JOIN_KEY=qlj_… go run ./hello-client http://hello/
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"tiltas.openpanel.sh/go"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	url := "http://hello/"
	if len(os.Args) > 1 {
		url = os.Args[1]
	}
	// Stopped or timed out, it still runs Close: the Device leaves the Network.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()

	srv := &tiltas.Server{}
	defer srv.Close()
	if err := srv.Up(ctx); err != nil {
		return err
	}

	req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
	if err != nil {
		return err
	}
	res, err := srv.HTTPClient().Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()
	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("%s: %s", url, res.Status)
	}
	_, err = io.Copy(os.Stdout, res.Body)
	return err
}
```

```sh
TILTAS_NAME=client go run ./hello-client http://hello/
```

**Python**

```python title="examples/python/client.py"
"""Calls a Service by name over a Tiltas Network and prints the answer.

    TILTAS_JOIN_KEY=qlj_… python client.py http://hello/
"""

import sys

import tiltas

url = sys.argv[1] if len(sys.argv) > 1 else "http://hello/"

with tiltas.Server() as server:
    with server.urlopen(url) as res:
        print(res.read().decode(), end="")
```

```sh
TILTAS_NAME=client python client.py http://hello/
```

**Node.js**

```js title="examples/node/client.mjs"
// Calls a Service by name over a Tiltas Network and prints the answer.
//
//   TILTAS_JOIN_KEY=qlj_… node client.mjs http://hello/
import { Server } from 'tiltas';

const url = process.argv[2] ?? 'http://hello/';
const tiltas = await new Server().up();
try {
  const res = await tiltas.fetch(url);
  if (!res.ok) throw new Error(`${url}: ${res.status} ${res.statusText}`);
  process.stdout.write(await res.text());
} finally {
  await tiltas.close();
}
```

```sh
TILTAS_NAME=client node client.mjs http://hello/
```

It prints:

```text
hello client
```

The client joined, called `hello` by its Service name, and left. The server learned who called from the Network
itself, not from anything the client sent. Any client language works with any server language.

## Next

- Call the server by its Device name, `http://hello-server/`, after an Access rule from the client to that Device; or
  reach a database: `Dial` (Go) or `dial` (Python, Node.js) any TCP port by name.
- Keep a Device across restarts with the persistent option; see your language's page.
- Read the [limitations](/docs/sdks/limitations) before you ship.
