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.
API references
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 |
Opening a connection
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")Connection URLs
The scheme of the URL chooses the connection type:
| Scheme | Connection type | Description |
|---|---|---|
ws:// | WebSocket | Unencrypted stateful connection |
wss:// | WebSocket | TLS-encrypted stateful connection |
http:// | HTTP | Unencrypted stateless connection |
https:// | HTTP | TLS-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.
Selecting a namespace and database
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.
Connection options
FromEndpointURLStringWithOptions and FromConnectionWithOptions take options that change how the client behaves. With no options, they do what FromEndpointURLString and FromConnection do.
| Option | Default | What it does |
|---|---|---|
WithVersionCheck(enabled) | Off | Makes connecting fail on a server outside the supported versions. |
WithReconnect(enabled) | On, for WebSocket | Reconnects when the connection is lost, and restores the session. |
WithReconnectAttempts(attempts) | 5 | Sets how many consecutive attempts the client makes to reconnect. |
WithReconnectDelay(min, max) | 1s, 1m | Sets the wait before each attempt to reconnect. |
WithTokenRenewal(enabled) | Off | Renews a token pair before the access token expires. |
WithTokenExpiryMargin(margin) | 1m | Sets 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.
Server version check
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
}Request timeouts
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.
Checking server health
.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.
Server version and CBOR version
.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)4.0.0The 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())cbor.2A 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.
Connection status
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.
Using a custom connection
To configure the connection itself, create it yourself. Then pass it to FromConnection or FromConnectionWithOptions. The module has three connection packages:
| Package | Connection |
|---|---|
pkg/connection/gorillaws | WebSocket, with gorilla/websocket. FromEndpointURLString uses it for ws:// and wss://. |
pkg/connection/gws | WebSocket, with lxzan/gws. |
pkg/connection/http | HTTP. 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:
| Field | What it sets |
|---|---|
Marshaler, Unmarshaler | The CBOR codec. The deprecated models.CborMarshaler and models.CborUnmarshaler support plain CBOR only. |
Logger | The logger for the connection. nil turns logging off. |
DisableCBORv2 | Offers plain CBOR only, even to a SurrealDB 4.0 server. |
Effect of connection protocol on token and session duration
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.


You can configure token and session durations using the DURATION clause in DEFINE ACCESS METHOD or DEFINE USER statements.
Learn more about token and session duration in the security best practices documentation.
Closing a connection
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.
Learn more
DB API reference for complete method signatures and parameters
Authentication for signing in and managing tokens
Reliable connections for reconnection and the connection status
Error handling for connection and authentication errors