Skip to content

Concepts

Connecting to SurrealDB

The Go SDK connects to SurrealDB over WebSocket or HTTP. FromEndpointURLString reads the scheme of a URL, creates the matching connection, and connects it. This page covers opening and closing a connection, the options that change how a client behaves, the health and version checks, and custom connections.

Function

Description

surrealdb.FromEndpointURLString(ctx, url)

Creates a client from a URL and connects it

surrealdb.FromEndpointURLStringWithOptions(ctx, url, opts...)

Creates a client from a URL, configured by options

surrealdb.FromConnection(ctx, conn)

Creates a client from a connection you build yourself

db.Use(ctx, ns, db)

Selects a namespace and database

db.Health(ctx)

Checks that the server is up

db.Version(ctx)

Returns the version of the server

db.CBORVersion()

Returns the CBOR version the connection uses

db.Close(ctx)

Closes the connection and releases its resources

Call FromEndpointURLString with a context.Context and the address of the server. It returns a *DB that is already connected:

ctx := context.Background()

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}
defer db.Close(ctx)

The context limits the connection attempt. Use context.WithTimeout to set how long the attempt can block on an unreliable network:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

db, err := surrealdb.FromEndpointURLString(ctx, "ws://localhost:8000")

The scheme of the URL chooses the connection type:

SchemeConnection typeDescription
ws://WebSocketUnencrypted stateful connection
wss://WebSocketTLS-encrypted stateful connection
http://HTTPUnencrypted stateless connection
https://HTTPTLS-encrypted stateless connection

A WebSocket connection is long-lived and stateful. It supports every feature of the SDK, including live queries, sessions, interactive transactions, streaming results and automatic reconnection.

An HTTP connection is stateless. The client keeps the namespace, database, variables and token itself, and sends them with each request. Live queries, sessions and interactive transactions are not available over HTTP. Over HTTP, QueryStream returns the whole result at once.

A connection to a mem://, memory or surrealkv:// URL fails with the error embedded database not enabled. To run SurrealDB inside a Go program, use the separate surrealdb.c.go module.

After connecting, call .Use() to select the namespace and database that later requests work in:

if err := db.Use(ctx, "surrealdb", "docs"); err != nil {
	log.Fatal(err)
}

You can call .Use() again at any time to switch to another namespace or database on the same connection.

FromEndpointURLStringWithOptions and FromConnectionWithOptions take options that change how the client behaves. With no options, they do what FromEndpointURLString and FromConnection do.

OptionDefaultWhat it does
WithVersionCheck(enabled)OffMakes connecting fail on a server outside the supported versions.
WithReconnect(enabled)On, for WebSocketReconnects when the connection is lost, and restores the session.
WithReconnectAttempts(attempts)5Sets how many consecutive attempts the client makes to reconnect.
WithReconnectDelay(min, max)1s, 1mSets the wait before each attempt to reconnect.
WithTokenRenewal(enabled)OffRenews a token pair before the access token expires.
WithTokenExpiryMargin(margin)1mSets how long before expiry the client renews a token.
db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "wss://example.surrealdb.cloud",
	surrealdb.WithVersionCheck(true),
	surrealdb.WithReconnectAttempts(10),
	surrealdb.WithTokenRenewal(true),
)

Reliable connections explains reconnection, and Authentication explains token renewal.

The SDK supports SurrealDB 3.3.0 and later versions before 5.0.0. With WithVersionCheck(true), the client asks the server for its version when it connects. If the version is outside that range, connecting fails with an UnsupportedVersionError:

db, err := surrealdb.FromEndpointURLStringWithOptions(ctx, "ws://localhost:8000",
	surrealdb.WithVersionCheck(true),
)

var uv *surrealdb.UnsupportedVersionError
if errors.As(err, &uv) {
	log.Fatalf("SurrealDB %s is not supported", uv.Version)
}

The check is off by default, because it adds a request to every connection. This extra request matters to code that opens a new connection for each request. The check also fails on a server that does not answer the version request, such as one started with --deny-rpc version.

To check a version without connecting, use IsVersionSupported. Use IsVersionInRange to check for a feature that a later release added:

ver, err := db.Version(ctx)
if err != nil {
	log.Fatal(err)
}

if surrealdb.IsVersionInRange(ver.Version, "4.1.0", surrealdb.MaximumServerVersion) {
	// use a feature that SurrealDB 4.1 added
}

Each request waits for its answer until its context ends or the connection's timeout passes. The timeout is 30 seconds for a WebSocket connection and 10 seconds for an HTTP connection. A request that times out returns an error that wraps context.DeadlineExceeded. You can check for this error with errors.Is.

Pass a context with a deadline to limit a single request:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

results, err := surrealdb.Query[[]Person](ctx, db, "SELECT * FROM person", nil)

To change the timeout of every request, build the connection yourself, as shown in Using a custom connection. Then call SetTimeOut on a gorillaws connection, or SetTimeout on an http connection. A WebSocket timeout of 0 turns the timeout off. The context is then the only limit on a request.

.Health() sends GET /health to the server over HTTP, whichever transport the client uses. The request needs no authentication. .Health() returns nil when the server answers with a 2xx status:

if err := db.Health(ctx); err != nil {
	var he *surrealdb.HealthError
	if errors.As(err, &he) {
		log.Printf("unhealthy: %d %s", he.StatusCode, he.Body)
	}
}

The server answers with another status when it cannot reach its datastore. The HealthError then holds the status and the start of the body. On a network failure, .Health() returns the error of the HTTP request.

.Version() returns the version, build and timestamp that the server reports:

ver, err := db.Version(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println(ver.Version)
Possible output
4.0.0

The SDK sends requests as CBOR. SurrealDB 4.0 adds cbor.2, a version of the CBOR protocol. Over cbor.2, the sized numbers and the date, time, timestamp, interval, bigdecimal and regex kinds of SurrealDB 4.0 keep their types. The SDK offers cbor.2 when it connects. If the server does not accept cbor.2, the SDK uses plain CBOR. Servers before 4.0 do not accept cbor.2. .CBORVersion() returns the version the connection uses:

fmt.Println(db.CBORVersion())
Output with SurrealDB 4.0
cbor.2

A WebSocket connection chooses the version in its handshake. An HTTP connection sends plain CBOR until the server first answers in cbor.2. As a result, a new HTTP client reports cbor until the server answers its first request, such as .SignIn(). With WithVersionCheck(true), the version request is the first request, so with SurrealDB 4.0 the client uses cbor.2 from the start. Value types lists what changes between the two.

A WebSocket client that reconnects reports the state of its connection. .Status() returns the state, and .OnStatus() calls a function at each change:

stop := db.OnStatus(func(ev surrealdb.StatusEvent) {
	log.Printf("connection %s (attempt %d): %v", ev.Status, ev.Attempt, ev.Err)
})
defer stop()

See Reliable connections for the states and events.

To configure the connection itself, create it yourself. Then pass it to FromConnection or FromConnectionWithOptions. The module has three connection packages:

PackageConnection
pkg/connection/gorillawsWebSocket, with gorilla/websocket. FromEndpointURLString uses it for ws:// and wss://.
pkg/connection/gwsWebSocket, with lxzan/gws.
pkg/connection/httpHTTP. FromEndpointURLString uses it for http:// and https://.
import (
	"net/url"
	"time"

	surrealdb "github.com/surrealdb/surrealdb.go/v2"
	"github.com/surrealdb/surrealdb.go/v2/pkg/connection"
	"github.com/surrealdb/surrealdb.go/v2/pkg/connection/gorillaws"
)

u, err := url.ParseRequestURI("ws://localhost:8000")
if err != nil {
	log.Fatal(err)
}

conf := connection.NewConfig(u)
conn := gorillaws.New(conf).SetTimeOut(time.Minute)

db, err := surrealdb.FromConnectionWithOptions(ctx, conn,
	surrealdb.WithVersionCheck(true),
)

FromConnection calls .Connect(ctx) on the connection for you. A gorillaws or gws connection reconnects in the same way as a connection from FromEndpointURLString. For a connection with its own retry strategies, see the rews package.

connection.NewConfig sets the CBOR codec to surrealcbor. Set the fields of the configuration before you create the connection:

FieldWhat it sets
Marshaler, UnmarshalerThe CBOR codec. The deprecated models.CborMarshaler and models.CborUnmarshaler support plain CBOR only.
LoggerThe logger for the connection. nil turns logging off.
DisableCBORv2Offers plain CBOR only, even to a SurrealDB 4.0 server.

WebSocket connections (ws://, wss://) are long-lived and stateful. After authentication, the session persists for the lifetime of the connection. The session duration defaults to NONE, meaning it never expires unless configured otherwise.

HTTP connections (http://, https://) are short-lived and stateless. The SDK sends the access token from the sign-in with each request, so requests fail when the token expires. The token duration defaults to 1 hour.

The figure below shows which duration ends the session in each case, with the default durations.

A timeline over two hours shows which duration ends a session when the token duration is the default of one hour. A WebSocket connection that signed in with credentials keeps one session, and with the default session duration of NONE it keeps working after the token that signin returned has expired. A WebSocket connection that authenticated with a token has its session end when the token expires, and later queries fail with 'The session has expired'. Over HTTP, requests that send the token in an Authorization Bearer header succeed until the token expires and then fail with 401, while requests that send Basic credentials sign in again each time and keep succeeding. Over HTTP, the JavaScript, Python and Go SDKs send the token; the Rust, Java and .NET SDKs send a system user's username and password with every request, and a token for record users.A timeline over two hours shows which duration ends a session when the token duration is the default of one hour. A WebSocket connection that signed in with credentials keeps one session, and with the default session duration of NONE it keeps working after the token that signin returned has expired. A WebSocket connection that authenticated with a token has its session end when the token expires, and later queries fail with 'The session has expired'. Over HTTP, requests that send the token in an Authorization Bearer header succeed until the token expires and then fail with 401, while requests that send Basic credentials sign in again each time and keep succeeding. Over HTTP, the JavaScript, Python and Go SDKs send the token; the Rust, Java and .NET SDKs send a system user's username and password with every request, and a token for record users.

You can configure token and session durations using the DURATION clause in DEFINE ACCESS METHOD or DEFINE USER statements.

Note

Learn more about token and session duration in the security best practices documentation.

Call .Close() to close the connection and release its resources:

db.Close(ctx)

Call defer db.Close(ctx) directly after you create the connection. The connection then closes even when a later step fails. After .Close(), requests return surrealdb.ErrClientClosed.

Was this page helpful?

Last updated